Skip to content

Commit

Permalink
Clear up lack of clarity around equality/identity
Browse files Browse the repository at this point in the history
  • Loading branch information
leonardehrenfried committed Sep 22, 2023
1 parent 4f8e41c commit 630733d
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ public class PredicateUtils {
* <p>
* This is useful for removing duplicates from a stream where the key to be compared is not the
* entity itself but a field of it.
* <p>
* Note: Duplicate check is based on equality not identity.
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@

class PredicateUtilsTest {

private static final String HELLO = "HELLO";
private static String makeHello() { return new String("HELLO");}

@Test
void distinctByKey() {
var first = new Wrapper(10, HELLO);
var first = new Wrapper(10, makeHello());
var last = new Wrapper(20, "HI");
var stream = Stream.of(first, new Wrapper(20, HELLO), last);
var stream = Stream.of(first, new Wrapper(20, makeHello()), last);

var deduplicated = stream.filter(PredicateUtils.distinctByKey(w -> w.string)).toList();

Expand Down

0 comments on commit 630733d

Please sign in to comment.