See Collectors.partitioningBy , which takes a predicate as an argument. You must use Stream.collect to use it.
The result is a map with two Boolean entries: for the true key, you have a List containing stream elements that match the predicate, while for the false key you have a List containing the elements that don't match.
Note that Collectors.partitioningBy has an overloaded version that takes a second argument, which is a top-down collector that you can use if you want each section to be put together in something other than a list.
In your example, you can use it as follows:
Map<Boolean, List<Integer>> partition = intList.stream() .collect(Collectors.partitioningBy(i -> i < 3)); List<Integer> lessThan = partition.get(true);
I would also like to highlight an important point, taken from a comment posted by @Holger in a related question:
Collectors.partitioningBy will always have a result for true and false in Map , that is, in an empty list, if not a single item falls into this group, and not null .
This feature was added to jdk9 docs as an API note (again, this was observed by user @Holger):
If the section has no elements, its value in the resulting map will be empty.
source share