Created
June 29, 2025 02:04
-
-
Save rokon12/7c7e6cb2636b1839daaee8346e1f28eb to your computer and use it in GitHub Desktop.
Code snippet from The Coding Café - snippet-5.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static <T, K> Gatherer<T, ?, T> distinctByKey(Function<T, K> keyExtractor) { | |
return Gatherer.of( | |
HashSet::new, // 1️⃣ State: Set to track seen keys | |
(state, element, downstream) -> { | |
K key = keyExtractor.apply(element); // 2️⃣ Extract the key | |
if (state.add(key)) { // 3️⃣ If key is new (add returns true) | |
return downstream.push(element); // 4️⃣ Pass element downstream | |
} | |
return true; // 5️⃣ Continue processing | |
} | |
); | |
} | |
List<String> words = List.of("hello", "world", "java", "gatherers", "stream", "api"); | |
List<String> distinctByLength = words.stream() | |
.gather(distinctByKey(String::length)) // Using length as the key | |
.toList(); | |
System.out.println("Distinct by length: " + distinctByLength); | |
// Output: [hello, java, gatherers, api] | |
// ↑ ↑ ↑ ↑ | |
// len=5 len=4 len=9 len=3 | |
// Note: "world"(5) and "stream"(6) are filtered out as duplicates |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment