Reputation: 55
I have a list which I need to iterate on the basis of certain conditions as below:
StringBuilder sb = new StringBuilder();
list.stream().forEach(l-> {
if(l.contains("(")){
sb.append("a");
} else
sb.append("b");
});
How to do the same operation using filter of stream.
Upvotes: 0
Views: 1477
Reputation: 433
you can try this,
List<String> val = Arrays.asList("There", "(may)", "(not)", "exist", "brackets");
StringBuilder sb = val.stream()
.map(a -> a.contains("(")? "a": "b")
.collect(StringBuilder::new,StringBuilder::append,StringBuilder::append);
System.out.println(sb);
Output:
baabb
Upvotes: 1
Reputation: 86324
It’s not exactly what you asked for, but I thought it was worth presenting as an idea to consider.
List<String> list = List.of("There", "(may)", "(not)", "exist", "brackets");
String result = list.stream()
.map(s -> s.contains("(") ? "a" : "b")
.collect(Collectors.joining());
System.out.println(result);
Output is:
baabb
Stream operations should generally be free from side effects, and their effect rather come out of their terminal operation. If you do need a StringBuilder
, construct one after the end of the stream opeartion:
StringBuilder sb = new StringBuilder(result);
Upvotes: 0
Reputation: 4857
You can use map()
and put your condition
StringBuilder sb = new StringBuilder();
list.stream().map(str -> {
if (str.contains("(")) {
return "a";
}
return "b";
}).forEach(sb::append);
Upvotes: 0