Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return non Class type from Collectors.partitioningBy

In this example

Stream<MyClass>stream = Stream.of(new MyClass(5),new MyClass(15),new MyClass(8),new MyClass(12));

Map<Boolean, List<Integer>> map =
        stream.collect(Collectors.partitioningBy(a->a.getNum()<10));

the stream.collect retrieves a map of Boolean and List<MyClass> so it doesn't work. What should I do to return a map of Boolean and List<Integer> instead?

like image 635
T4l0n Avatar asked Nov 21 '25 06:11

T4l0n


1 Answers

Normally, when you want a different aggregation in a groupingBy or partitioningBy operation, you’d do it by specifying another Collector like in:

Map<Boolean, List<Integer>> map
    = stream.collect(Collectors.partitioningBy(a -> a.getNum()<10,
        Collectors.mapping(MyClass::getNum, Collectors.toList())));

however, when both, the partitioning function and the aggregation function, work on the same property, it’s much easier to map the elements to that property value upfront:

Map<Boolean, List<Integer>> map2
    = stream.map(MyClass::getNum).collect(Collectors.partitioningBy(num -> num<10));
like image 115
Holger Avatar answered Nov 23 '25 18:11

Holger