Pkdrc
Pkdrc

Reputation: 55

how to use filter a list and append to stringbuilder using stream() java8

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

Answers (3)

Abhishek
Abhishek

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

Anonymous
Anonymous

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

0xh3xa
0xh3xa

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

Related Questions