user2336315 user2336315 - 1 month ago 7
Java Question

What's the purpose of partitioningBy

For example, if I would partition a some elements I could do something like:

Stream.of("I", "Love", "StackOverflow")
.collect(Collectors.partitioningBy(s -> s.length() > 3))
.forEach((k, v) -> System.out.println(k+" => "+v));


which outputs:

false => [I]
true => [Love, StackOverflow]


But for me
partioningBy
is only a subcase of
groupingBy
. Although the former accepts a
Predicate
as parameter while the latter a
Function
, I just see a partition as a normal grouping function.

So the same code does exactly the same thing:

Stream.of("I", "Love", "StackOverflow")
.collect(Collectors.groupingBy(s -> s.length() > 3))
.forEach((k, v) -> System.out.println(k+" => "+v));


which also results in a
Map<Boolean, List<String>>
.

So is there any reason I should use
partioningBy
instead of
groupingBy
? Thanks

Answer

partitioningBy is slightly more efficient, using a special Map implementation optimized for when the key is just a boolean.

(It might also help to clarify what you mean; partitioningBy helps to effectively get across that there's a boolean condition being used to partition the data.)