0

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.

1
  • If the builder has to be empty initially, and you need to join "a" or "b" based on the iterations, then use Collections.joining as with transformation under map as l.contains("(") ? "a" : "b" once you stream. Commented Jun 20, 2021 at 18:40

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.