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