I extract some Data into a Arraylist. And in every Item there are several line breaks (\n) that I want to get rid of afterwards.
I´ve tried to do this:
public List<String> MemberIDList() {
// Getting the ArrayList
idList = listProjection.getIDListOfMembers();
for (int i = 0; idList.size() > i; i++) {
String item = idList.get(i);
item.replaceAll("\n", "");
}
return idList;
}
If I print that out on the console, it still contains all the line breaks:
The ID ...... (not null)
145
145
Thanks
EDIT: I also want to filter unnecessary whitespace. Is ther a better option than running the answers down below twice. There are spaces --------------------- this huge.
idList.replaceAll(item -> item.replaceAll("\\s{2,}", "").trim());
I got it :D
Change
item.replaceAll("\n", "");
to
idList.set(i,item.replaceAll("\n", ""));
item.replaceAll doesn't modify the state of the String referenced by item (which is impossible, since String is immutable). It returns a new String instead.
You can replace all your method to be like so :
public List<String> memberIDList() {
idList.replaceAll(item -> item.replaceAll("\n", ""));
return idList;
}
You can stream and map them:
idList.stream()
.map(str -> str.replaceAll("\n", ""))
.collect(Collectors.toList());
This will apply function str -> str.replaceAll("\n", "") to every element and collect them back to list. You can use this instead of your MemberIDList method.
P.S.: Method names are starting with lowercase in java.
Related
Currently im learning about stream and want to implement a method which accepts a string. The String starts with a certain word and ends with the same. The given example is "breadtunabread". The method return the word in between the bread.
public String getTopping(String s){
Stream<String> stream = Stream.of(s);
stream.filter(t -> t.startsWith("bread") && t.endsWith("bread")).
forEach(t -> Stream.of(t.split("bread")[1]).collect(Collectors.toList()));
}
I'd like to either save it to a List or change it directly so it returns a String.
Is it possible to get the first value from the stream and not use collect?
I somehow made it work using forEach and adding the value to an ArrayList and returning it but i'd like to know whether there is a way to do it directly using the stream.
Thanks in advance.
And to return just a String:
public String getTopping(String s, String toReplace) {
Stream<String> stream = Stream.of(s);
return stream.filter(t -> t.startsWith(toReplace) && t.endsWith(toReplace))
.findFirst()
.map(t -> t.replaceAll(toReplace, ""))
.orElseThrow(RuntimeException::new);
//.orElseThrow(() -> new NoBreadException("s"));
}
Stream<String> stream = Stream.of("breadtunabread");
List<String> stringList =
stream
.filter(t -> t.startsWith("bread") && t.endsWith("bread"))
.map(t -> (t.split("bread")[1]))
.collect(Collectors.toList());
Is this what you are looking for?
What others mentioned are correct that this is completely unnecessary. I posted this as you have mentioned that yuo are learning streams.
Just like #Naman pointed out, you don't need a Stream for this. String#replaceAll will quite literally replace all instances of the String (bread) with empty String values and in the end you get you're topping. Added the base parameter in case you're a monster like me and eat cheese between pieces of ham.
public static String getTopping(String value, String base) {
return value.replaceAll(base, "");
}
String topping = getTopping("breadtunabread", "bread")
Assuming you have a List of items you want to get the toppings of.
List<String> sandwhiches = Arrays.asList(
"breadtunabread",
"breadchickenbread",
"breadcheesebread",
"breadturkeybread",
"breadlambbread"
);
List<String> toppings = sandwhiches.stream()
.map(sandwhich -> getTopping(sandwhich, "bread"))
.collect(Collectors.toList());
Result
[tuna, chicken, cheese, turkey, lamb]
Let say I have an array list with names and the names are stored like this...
John(2),
Bob(anytext),
Rick
I'm trying to iterate over my array list and check for "(" basically and just take the rest of the string behind it and return that as a string, and null if nothing there. I've seen methods to do similar things but I can't seem to find something to just return the rest of the string if it finds the "("
for(int i=0; i<list.size(); i++) {
String s = list.get(i);
int x = s.indexOf('(');
if(x==-1) break;
return s.substring(x+1);
}
Pass the strings you want to check to a method that does something like this:
if(str.contains("(")){
return str.substring(str.indexOf("("));
}else{
return null;
}
Java 8 version
List<String> list = Arrays.asList("John(2)", "Bob(anytext)", "Rick");
String result = list.stream()
.filter(x -> x.contains("("))
.findFirst()
.map(x -> x.substring(x.indexOf("(")))
.orElse(null);
I'm developing an Android app where I get a List of names (Strings) from a SQLite database. Then, I show them on a List of Cardviews.
I'm also given a substring, so I'd like to check if any of the elements of the original List contains that substring on it.
I'm having problems using LIKE in the SQLite query, so I've just fixed it with a try{ } catch (Exception e) { }, but I don't feel so comfortable with it.
Anyway, since I originally have all of the names stored in the List of Strings, I don't really need to fecth the new ones again from the database, I can just search them on the original List of Strings. But I don't know how.
For example, let's say the List of String has this 5 elements:
Hello
Wall
Helicopter
Chair
Hell
And I'm given the substring Hel. I should get the Hello, Helicopter and Hell strings, since all of them contain the substring Hel.
Any ideas on how to achieve this goal?
It's not that I want to fix it this way. I sincerely would like to know what's the most efficient, if retrieveing the data again from the database, or search it from the List of Strings.
EDIT: I originally said that I was using the CONTAINS query, but I missed the word. I just meant the LIKE query. I'm actually using it, and it works fine but I don't really know what's the most efficient in my case.
Thanks in advance.
Here is my suggestion
public boolean isSubstring(String str, String key) {
if(key.length() > str.length()) return false;
for(int i = 0; i <= str.length() - key.length(); i++) {
if( key.equals(str.substring(i, i + key.length())) ) return true;
}
return false;
}
public List<String> findStings(List<String> list, String key) {
List<String> newList = new ArrayList<>();
for(int i = 0; i < list.size(); i++) {
if(isSubstring(list.get(i), key)) {
newList.add(list.get(i));
}
}
return newList;
}
If you are working with Java 8 you can replace the for-loop of the second method as:
for(String str: list) {
if(isSubstring(str, key)) newList.add(str);
}
or simply as:
list.stream().filter((str) -> (isSubstring(str, key))).forEach((str) -> { newList.add(str); });
If you're using Java 8:
List<String> filteredList = myList.stream().filter(s -> s.contains("Hel")).collect(Collectors.toList());
If you're using anything earlier, use a for each loop:
List<String> filteredList = new ArrayList<String>();
for(String s : myList)
if(s.contains("Hel")
filteredList.add(s);
I have
Map<String, String> prefixes
and
List<String> annotationProperties
And I am trying to get the string output of
prefix: annotationProperty
for each entry (they were entered in order).
Is there a for loop I could use to concatenate these? I need to return the entries as a List<String> to use in an XML output.
Thank you!
I assume annotationProperties is a key for prefix map. If that is the case then in Java 8 you can do this:
List<String> output = annotationProperties.stream()
.map(prop -> String.format("%s: %s", prefix.get(prop), prop))
.collect(Collectors.toList());
stream is called so you can use stream functions such as map and collect
map is called to transform the strings in annotationProperties into your desired output
and collect is called to convert the stream back into a list
If you want to use a for loop then you could also do it like this:
// The end size is known, so initialize the capacity.
List<String> output = new ArrayList<>(annotationProperties.size());
for (String prop : annotationProperties){
output.add(String.format("%s: %s", prefix.get(prop), prop));
}
Can a set a variable equal to .collect(Collectors.toList()); ?
We already have one! In both cases we made a variable output which is a list of Strings formatted as prefix: property. If you want to use this list then you can loop over it like this:
for (String mystring : output) {
// do xml creation with mystring
}
or like this:
for (int i = 0; i < output.size(); i++){
String mystring = output.get(i);
// do xml creation with mystring
}
or like this:
output.stream().forEach(mystring -> {
// do xml creation with mystring
});
I am using streams to concatenate a series of strings and add commas between them, but there must be no comma at the beginning or the end of the result string.
import java.util.Arrays;
import java.util.List;
public class QuestionNine {
public static void main(String[] args) {
new QuestionNine().launch();
}
public void launch(){
List<String> words = Arrays.asList("Hello", "Bonjour", "engine", "Hurray", "What",
"Dog", "boat", "Egg", "Queen", "Soq", "Eet");
String result = (words.stream().map(str -> str + ",").reduce("", (a,b) -> a + b));
result = result.substring(0, result.length() -1); //removes last comma
System.out.println(result);
}
}
Instead of using the String.substring() method at the end to get rid of the last comma, is there a way i could have deleted the last comma within the stream pipeline?
The usual idiom is to use the joining Collector with Streams.
String res = words.stream().collect(Collectors.joining(","));
Although you can use String.join in your case since you are directly dealing with an Iterable.
String res = String.join(",", words);
The problem with your approach is that the mapping function you apply impose that there will be a comma at the end of each word. You could get rid of this mapping; and apply the reduce function such that you get the desired output:
.stream().reduce("", (a,b) -> a.isEmpty() ? b : a+","+b);
but I don't recommend this.
Yes, you can use Collectors.joining() here:
String joined = words.stream().collect(Collectors.joining(", "));
Or, also as noted from comments, you can use newly added String.join(CharSequence, Iterable) method.
String joined = String.join(", ", words);