Stream Distinct By Key Idiom
Deduplicate a stream by a chosen key with a seen-set filter, since distinct() only compares whole records by equals.
Code
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class StreamDistinctByKey {
record Event(String userId, String action) {}
public static void main(String[] args) {
List<Event> events = List.of(
new Event("u1", "login"),
new Event("u2", "login"),
new Event("u1", "search"),
new Event("u3", "login"),
new Event("u1", "logout"));
// distinct() 只按整条记录 equals 去重;按字段去重要自己维护已见键
Set<String> seen = ConcurrentHashMap.newKeySet();
List<Event> firstPerUser = events.stream()
.filter(event -> seen.add(event.userId())) // add 返回 false 表示已见过
.toList();
System.out.println("first per user: " + firstPerUser);
// 反向遍历 + 同一套惯用法:取每个用户最后一条
Set<String> seenReversed = ConcurrentHashMap.newKeySet();
List<Event> lastPerUser = events.reversed().stream()
.filter(event -> seenReversed.add(event.userId()))
.toList();
System.out.println("last per user: " + lastPerUser);
}
}How it works
the classes StreamDistinctByKey and Event and the function main cover the runnable surface of Stream Distinct By Key Idiom.
The pipeline is a stream: source, lazy intermediate steps, one terminal collector.
Points of care
- No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
Using it
Its defining line is public static void main(String[] args)
Output lines are prefixed (first per user:, last per user:), so the printed sequence mirrors the code path.
Key statements
.filter(event -> seen.add(event.userId())) // add 返回 false 表示已见过
.toList();
List<Event> lastPerUser = events.reversed().stream()
.filter(event -> seenReversed.add(event.userId()))
.toList();
Interactive Tools for This Topic
FAQ
- What does Stream Distinct By Key Idiom print when run?
- Run it as a complete program — the output lines carry labels such as `first per user:`, `last per user:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.