In Java, if you have a collection (e.g., a List) of objects of type Foo, and you want to get a list of distinct objects based on a specific field — say fieldA — you can use Java Streams with the distinct() method or Collectors.toMap() / Collectors.groupingBy().
However, since distinct() works based on the equals() and hashCode() methods, it's not directly usable unless you override those methods. Instead, for distinct by a specific field, the idiomatic way is to use Collectors.toMap() or filter() with a Set.
✅ Recommended approach: Using Collectors.toMap()
Assuming:
java
class Foo {
private String fieldA;
private int fieldB;
// constructor, getters, etc.
public String getFieldA() { return fieldA; }
}
Example: Get distinct Foo objects by fieldA
java
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Foo> fooList = Arrays.asList(
new Foo("apple", 1),
new Foo("banana", 2),
new Foo("apple", 3),
new Foo("orange", 4)
);
List<Foo> distinctByFieldA = fooList.stream()
.collect(Collectors.toMap(
Foo::getFieldA, // key: fieldA
foo -> foo, // value: the Foo object itself
(existing, replacement) -> existing // or choose which one to keep
))
.values()
.stream()
.collect(Collectors.toList());
System.out.println(distinctByFieldA);
}
}
Explanation:
Collectors.toMap() groups entries by fieldA.
If duplicates are found ("apple" appears twice), the merge function (existing, replacement) -> existing keeps the first encountered one.
You can change this logic if you want to pick the last one instead.
🆚 Alternative: Use filter() with a mutable set
This method preserves encounter order (important if you're using ordered streams like from a List):
java
Set<String> seen = new HashSet<>();
List<Foo> distinctByFieldA = fooList.stream()
.filter(foo -> seen.add(foo.getFieldA())) // add returns false if already exists
.collect(Collectors.toList());
This is more efficient in some cases and maintains insertion order.
Summary:
Method
Preserves Order
Custom Merge Strategy
Notes
Collectors.toMap()
❌ (unless using LinkedHashMap)
✅
Good for maps and grouping
filter() + Set
✅
❌
Simpler and fast for lists
Let me know if you want to preserve the last occurrence instead of the first!