Consider I have a list with two types of data,one valid and the other invalid.
If I starting filter through this list, can i collect two lists at the end?
Can we collect two lists from Java 8 streams?
You cannot but if you have a way to group elements of the List
s according to a condition.
In this case you could for example use Collectors.groupingBy()
that will return Map<Foo, List<Bar>>
where the values of the Map
are the two List.
Note that in your case you don't need stream to do only filter.
Filter the invalid list with removeIf()
and add all element of that in the first list :
invalidList.removeIf(o -> conditionToRemove);
goodList.addAll(invalidList);
If you don't want to change the state of goodList
you can do a shallow copy of that :
invalidList.removeIf(o -> conditionToRemove);
List<Foo> terminalList = new ArrayList<>(goodList);
terminalList.addAll(invalidList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With