From 18d30c5f95b802bd1cf974cd9e1c199c80aefbbd Mon Sep 17 00:00:00 2001 From: James Date: Wed, 19 Jul 2023 10:41:26 +1200 Subject: [PATCH] Simplify distinctKeys methods * Concurrent sets only required if using parallel streams. * HashSet already has this functionality, using that makes the code tidier. --- .../core/streams/distinct/DistinctComplexTypes.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/howtodoinjava/core/streams/distinct/DistinctComplexTypes.java b/src/main/java/com/howtodoinjava/core/streams/distinct/DistinctComplexTypes.java index d6f921f..c19819f 100644 --- a/src/main/java/com/howtodoinjava/core/streams/distinct/DistinctComplexTypes.java +++ b/src/main/java/com/howtodoinjava/core/streams/distinct/DistinctComplexTypes.java @@ -57,7 +57,8 @@ public static void main(final String[] args) { @SuppressWarnings("unchecked") private static Predicate distinctByKeys(final Function... keyExtractors) { - final Map, Boolean> seen = new ConcurrentHashMap<>(); + // Set doesn't need to be `concurrent` unless using parallel streams. + final Set> seen = new HashSet<>(); return t -> { @@ -65,14 +66,16 @@ private static Predicate distinctByKeys(final Function... k .map(ke -> ke.apply(t)) .collect(Collectors.toList()); - return seen.putIfAbsent(keys, Boolean.TRUE) == null; + return seen.add(keys); }; } public static Predicate distinctByKeyClass(final Function keyExtractor) { - Map seen = new ConcurrentHashMap<>(); - return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + // Set doesn't need to be `concurrent` unless using parallel streams. + Set seen = new HashSet<>(); + // Set:add returns true if this set didn't already contain the specified value. + return t -> seen.add(keyExtractor.apply(t)); } } @@ -84,4 +87,4 @@ public CustomKey(final Person p) { this(p.firstName(), p.lastName()); } -} \ No newline at end of file +}