Using distinct After Transformations
What You'll Learn
You'll learn how to apply distinct() after map operations to remove duplicate results that emerge from transforming your data.
Why Transform First, Then Deduplicate?
Often when you use map() to extract properties or transform elements, multiple input elements produce the same output value. Applying distinct() after your transformation removes these duplicate results efficiently.
Think of it like sorting a bag of colored candies by color name. You might start with 20 candies, but after extracting just the color (the transformation), you might only have 5 unique colors. The distinct() operation gives you that final set of unique values.
The Pattern
The typical pattern looks like this:
stream()
.map(transformation)
.distinct()
// ... more operations
Practical Example
List<String> names = Arrays.asList("Alice", "Bob", "Alice", "Charlie", "Bob");
List<Integer> uniqueLengths = names.stream()
.map(String::length) // Transform: "Alice" -> 5, "Bob" -> 3, etc.
.distinct() // Remove duplicate lengths
.collect(Collectors.toList());
// Result: [5, 3, 7] (unique lengths only)
Without distinct(), you'd get [5, 3, 5, 7, 3] — the transformed values with duplicates intact.
When This Matters Most
- Extracting properties: Getting unique ages, departments, or categories from objects
- Calculations: Finding all unique results from mathematical transformations
- Normalization: Converting to uppercase/lowercase and finding unique values
Order of Operations
Place distinct() after the transformation that creates duplicates, not before. Applying it before won't help if the transformation itself generates duplicates.
Key Takeaway: Use distinct() after map() operations to efficiently remove duplicate values that result from transformations, giving you only the unique outcomes of your data mapping.