RFR: JDK-8170945: Collectors$Partition should override more Map methods

Tagir F. Valeev tvaleev at openjdk.org
Wed Apr 5 12:55:13 UTC 2023


On Wed, 5 Apr 2023 09:19:57 GMT, Viktor Klang <duke at openjdk.org> wrote:

> Adds overrides for common Map operations to avoid having to allocate the entrySet for Collectors$Partition maps.

Another thing I noticed is that `keySet()` of this map is a constant. If we want to preserve the order, we can use something like this:


    @Override
    public Set<Boolean> keySet() {
      return KeySet.INSTANCE;
    }

    private static class KeySet extends AbstractSet<Boolean> {
      private static final KeySet INSTANCE = new KeySet();
      
      public Iterator<Boolean> iterator() {
        return List.of(false, true).iterator();
      }

      public int size() {
        return 2;
      }

      @Override
      public int hashCode() {
        // Boolean.hashCode(true) + Boolean.hashCode(false)
        return 1237 + 1231;
      }

      @Override
      public boolean equals(Object o) {
        return o instanceof Set<?> s &&
                s.size() == 2 &&
                s.contains(false) && s.contains(true);
      }

      public boolean isEmpty() {
        return false;
      }

      public boolean contains(Object k) {
        return k instanceof Boolean;
      }

      @Override
      public void forEach(Consumer<? super Boolean> action) {
        Objects.requireNonNull(action);
        action.accept(false);
        action.accept(true);
      }

      @Override
      public String toString() {
        return "[false, true]";
      }
    }


Overengineering, probably? On the other hand, it might be useful to expose this set somewhere, like `Collections.booleans()`? This would allow using `for(boolean b: Collections.booleans()) {...}`. In our codebase, I see quite many loops like `for (boolean b : new boolean[]{false, true})`. Declaring it as a `SequencedSet` would be even more useful, as one may control the order via `Collections.booleans().reversed()`.

-------------

PR Comment: https://git.openjdk.org/jdk/pull/13347#issuecomment-1497432746


More information about the core-libs-dev mailing list