Java – what is the purpose of partitioning

For example, if I want to split some elements, I can do something like:

Stream.of("I","Love","Stack Overflow")
      .collect(Collectors.partitioningBy(s -> s.length() > 3))
      .forEach((k,v) -> Sy@R_404_2354@.out.println(k + " => " + v));

Its output:

false => [I]
true => [Love,Stack Overflow]

But for me, partioningby is just a sub - case of groupby Although the former takes a predicate as a parameter and the latter takes a function, I only see a partition as a normal grouping function

So the same code is exactly the same:

Stream.of("I","Stack Overflow")
       .collect(Collectors.groupingBy(s -> s.length() > 3))
       .forEach((k,v) -> Sy@R_404_2354@.out.println(k + " => " + v));

This also leads to map < Boolean, list < string > >

So is there any reason why I should use partioningby instead of groupby? thank you

Solution

Partitioningby will always return a mapping with two entries, one for the predicate true and the other for false

This is something groupsby won't do because it only creates entries when needed

In extreme cases, if you send an empty stream to partitionby, you will still get two entries in the map, and groupingby will return an empty map

Edit: as described below, this behavior is not mentioned in the Java documentation, but changing it will eliminate the added value currently provided by partitionby For Java 9, this is already in the specification

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>