What's the purpose of partitioningBy

前端 未结 5 589
粉色の甜心
粉色の甜心 2020-12-03 04:20

For example, if I intend to partition some elements, I could do something like:

Stream.of(\"I\", \"Love\", \"Stack Overflow\")
      .collect(Collectors.part         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 05:11

    partitioningBy will always return a map with two entries, one for where the predicate is true and one for where it is false. It is possible that both entries will have empty lists, but they will exist.

    That's something that groupingBy will not do, since it only creates entries when they are needed.

    At the extreme case, if you send an empty stream to partitioningBy you will still get two entries in the map whereas groupingBy will return an empty map.

    EDIT: As mentioned below this behavior is not mentioned in the Java docs, however changing it would take away the added value partitioningBy is currently providing. For Java 9 this is already in the specs.

提交回复
热议问题