RFR(s): JDK-8170943 Collectors.partitioningBy should specify that false and true entries are always present
Stuart Marks
stuart.marks at oracle.com
Thu Dec 8 22:48:50 UTC 2016
Hi all,
Please review this small spec change to the Collectors.partitioningBy() methods,
appended below. This collector returns Map<Boolean, Something>. The change
requires the implementation always to populate the returned map with entries for
both false and true keys.
The implementation already does this; the entries are initially populated with
values obtained by calling the supplier of the downstream collector.
The reason for this spec change that it's useful for applications to be able to
rely on this. The spec is currently silent about what entries will be present in
the map. If one or the other (or both!) of the entries can be absent, callers
would have to defend against this possibility. For example,
Map<Boolean, List<V>> map = stream.collect(partitioningBy(pred));
processResults(map.getOrDefault(false, List.of()),
map.getOrDefault(true, List.of()));
With the guarantee, it's safe instead to write:
Map<Boolean, List<V>> map = stream.collect(partitioningBy(pred));
processResults(map.get(false), map.get(true));
In fact, this code works today, it's just that it's not specified to work. It
should be.
Thanks,
s'marks
diff -r 7583c87dfe7c src/java.base/share/classes/java/util/stream/Collectors.java
--- a/src/java.base/share/classes/java/util/stream/Collectors.java Thu Dec 08
21:21:39 2016 +0000
+++ b/src/java.base/share/classes/java/util/stream/Collectors.java Thu Dec 08
14:39:31 2016 -0800
@@ -1268,6 +1268,8 @@
* to a {@code Predicate}, and organizes them into a
* {@code Map<Boolean, List<T>>}.
*
+ * The returned {@code Map} always contains mappings for both
+ * {@code false} and {@code true} keys.
* There are no guarantees on the type, mutability,
* serializability, or thread-safety of the {@code Map} or {@code List}
* returned.
@@ -1290,7 +1292,10 @@
* {@code Map<Boolean, D>} whose values are the result of the downstream
* reduction.
*
- * <p>There are no guarantees on the type, mutability,
+ * <p>
+ * The returned {@code Map} always contains mappings for both
+ * {@code false} and {@code true} keys.
+ * There are no guarantees on the type, mutability,
* serializability, or thread-safety of the {@code Map} returned.
*
* @param <T> the type of the input elements
More information about the core-libs-dev
mailing list