Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we collect two lists from Java 8 streams?

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?

like image 655
user10179187 Avatar asked Aug 04 '18 06:08

user10179187


1 Answers

Can we collect two lists from Java 8 streams?

You cannot but if you have a way to group elements of the Lists 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);
like image 66
davidxxx Avatar answered Oct 16 '22 22:10

davidxxx