Video in progress

You've written a distinctByKey predicate to make objects unique by one field. What are its risks, especially on a parallel stream?

A stateful predicate inside filter (seen.add(key)) breaks the stream rules: in parallel it is undefined which duplicate survives, a reused predicate remembers old state, and the Set grows with the whole key set. The deterministic variant is toMap(key, identity(), (a, b) -> a, LinkedHashMap::new).

📖 Answer

The popular solution from the internet:

static <T> Predicate<T> distinctByKey(Function<? super T, ?> key) {
    Set<Object> seen = ConcurrentHashMap.newKeySet();
    return t -> seen.add(key.apply(t));
}

List<User> unique = users.stream()
        .filter(distinctByKey(User::email))
        .toList();

On a sequential stream it works correctly and keeps the first user it meets for each email. The problems are elsewhere.

1. In parallel there is no "first". ConcurrentHashMap is thread-safe, but which thread adds a key first is random. The size of the result is right, but which User stays in the list differs on every run. If the duplicates aren't equal (say, one is an updated profile), that is a silent data bug.

2. The predicate is stateful and a reusable object. If someone pulls it out into a field:

private static final Predicate<User> UNIQUE_EMAIL = distinctByKey(User::email);  // a mistake

then on the second call seen is full and nothing gets through. This isn't visible in code review.

3. Memory. seen stores all the unique keys. On an infinite or very long stream (events from Kafka) this is a slow memory leak.

4. The stream contract. The Javadoc expects a stateless predicate from filter. Today the JDK calls it once, but the contract doesn't guarantee that.

A deterministic alternative:

Collection<User> unique = users.stream()
        .collect(Collectors.toMap(User::email, Function.identity(),
                (first, second) -> first,      // an explicit rule: the first one stays
                LinkedHashMap::new))
        .values();

Even in parallel, "first" follows source order: toMap's combiner puts the left part first. If which duplicate stays is a business rule (the most recent), write it explicitly in the merge function: (a, b) -> a.updatedAt().isAfter(b.updatedAt()) ? a : b.

If you need dedup on a long stream, use a cache bounded by a time window (Caffeine expireAfterWrite) or a unique constraint in the DB. On Java 24+, a custom Gatherer with explicit state does this job cleanly.