Arpit
Arpit

Reputation: 109

Multiple streams filter or forEach if-else

I have a small list which I have to separate into 2 lists based the value of an element. I am looking at 2 ways to do this -

  1. Either iterate the list twice using filters.
List<String> sublist1 = list.stream().filter(condition1).collect(ImmutableList.toImmutableList());
List<String> sublist2 = list.stream().filter(condition2).collect(ImmutableList.toImmutableList());
  1. Use a forEach in streams to assign values
List<String> sublist1 = new LinkedList<>();
List<String> sublist2 = new LinkedList<>();
list.stream().forEach(element -> {
    if(condition1) sublist1.add(element);
    else if (condition2) sublist2.add(element);
})

I wanted to know which way is better and more efficient to implement this?

Upvotes: 0

Views: 1678

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19565

If you have specifically two conditions resulting in two sub-lists and they are alternate that is only one of the two conditions may be true, you could use OR in filter or Predicate.or and then use Collectors.partitioningBy by either condition:

Map<Boolean, List<String>> sublistMap = list
        .stream()
        .filter(condition1.or(condition2))
        .collect(Collectors.partitioningBy(condition1, Collectors.toUnmodifiableList()));

List<String> sublist1 = sublistMap.get(Boolean.TRUE); // condition1
List<String> sublist2 = sublistMap.get(Boolean.FALSE); // condition2

Test

List<String> list = Arrays.asList("a", "b", "cc", "ddd", "aaaa", "vvv", "oo");
Predicate<String> condition1 = (s) -> s.contains("o");
Predicate<String> condition2 = (s) -> s.contains("a");

System.out.println(sublist1);
System.out.println(sublist2);

Output:

[oo]
[a, aaaa]

Upvotes: 2

Related Questions