简体   繁体   中英

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?

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);

The collector can only return a single object!

But you could create a custom collector that simply puts the stream elements into two lists, to then return a list of lists containing these two lists.

There are many examples how to do that.

另一个建议:使用lambda过滤,将要从流中过滤的元素添加到单独的列表中。

This is a way using Java 8 streams API. Consider I have a List of String elements: the input list has strings with various lengths; only strings with length 3 are valid.

List<String> input = Arrays.asList("one", "two", "three", "four", "five");
Map<Boolean, List<String>> map = input.collect(Collectors.partitioningBy(s -> s.length() == 3));
System.out.println(map); // {false=[three, four, five], true=[one, two]}

The resulting Map has only two records; one with valid and the other with not-valid input list elements. The map record with key=true has the valid string as a List : one, two. The other is a key=false and the not-valid strings: three, four, five.

Note the Collectors.partitioningBy produces always two records in the resulting map irrespective of the existence of valid or not-valid values.

If you need to classify binary (true|false), you can use Collectors.partitioningBy that will return Map<Boolean, List> (or other downstream collection like Set, if you additionally specify).

If you need more than 2 categories - use groupBy or just Collectors.toMap of collections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM