On Wed, 5 Apr 2023 12:49:31 GMT, Tagir F. Valeev <tval...@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()`. @amaembo I think ideally the entire Partition class could be replaced in favor of some `OrderedMap.of(Boolean.TRUE, forTrue, Boolean.FALSE, forFalse)` version. I'll let @stuart-marks chime in if there's other options on the table here. :) ------------- PR Comment: https://git.openjdk.org/jdk/pull/13347#issuecomment-1497483295