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 -
- 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());
- 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?
list.stream().forEach()
in the second case seems to be redundant, can be replaced withlist.forEach
or an equivalent loopfor(E element: list)