Dwayne Patel
Dwayne Patel

Reputation: 315

Using Java stream if a string is found then add to a list and also add an extra element

Using streams I want to populate a string array if a match is found with the matching strings and then add a new string to the array.

For example, this code will return a list:

List<String> source = Arrays.asList("one", "two", "three");
String s ="Two-three-six-seven";

List<String> target = source.stream()
        .filter(s.toLowerCase()::contains)
        .collect(Collectors.toList());

This creates a list (target) with "two" and "three" in it.

How can I now check that if the target list has a value then I add another value, e.g. "numbers", ending up with a list that has "two", "three", and "numbers"?

I know this is possible by adding more code outside of the stream but I am trying to do all inside the stream.

Upvotes: 0

Views: 752

Answers (1)

Oboe
Oboe

Reputation: 2723

As @Charlie Armstrong commented above, thats not a good use of a Stream. However, if you still have to use a Stream for any reason, you can use Collectors.collectingAndThen():

List<String> target = source.stream()
        .filter(s.toLowerCase()::contains)
        .collect(Collectors.collectingAndThen(Collectors.toList(),
                list -> list.isEmpty() ? list : 
                        Stream.concat(list.stream(), Stream.of("number"))
                                .collect(Collectors.toList())));

System.out.println(target);

Output

[two, three, number]

Upvotes: 2

Related Questions