Got it — your source is an (unordered) Set<Foo>, so the iteration order is non-deterministic.
To get exactly one Foo per fieldA and be sure the final list is in a predictable order, just do two simple things:
- Pick a rank / priority rule for duplicates (keep first? keep last? max fieldB? etc.).
- Collect into a sorted map (e.g.
TreeMap) so the keys (fieldA) are ordered.
Below are the most common flavours.
A) Keep the FIRST Foo per fieldA, sort the output ascending by fieldA
List<Foo> result = foos.stream() // foos is a Set<Foo>
.collect(Collectors.collectingAndThen(
Collectors.toMap(
Foo::getFieldA, // key = fieldA
Function.identity(), // value = Foo itself
(first, duplicate) -> first, // 👈 keep the first
TreeMap::new // 🔑 TreeMap ⇒ sorted by key
),
m -> new ArrayList<>(m.values()) // Map → List
));
Result list is now:
• unique by fieldA
• ordered: fieldA = apple, banana, cherry… (natural String order)
B) Keep the LAST Foo per fieldA, still ordered by fieldA
List<Foo> result = foos.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(
Foo::getFieldA,
Function.identity(),
(first, duplicate) -> duplicate, // 👈 keep the last
TreeMap::new
),
m -> new ArrayList<>(m.values())
));
C) Custom tie-breaker (e.g. keep the larger fieldB), ordered by fieldA
List<Foo> result = foos.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(
Foo::getFieldA,
Function.identity(),
(a, b) -> a.getFieldB() >= b.getFieldB() ? a : b, // 👈 your rule
TreeMap::new
),
m -> new ArrayList<>(m.values())
));
D) Need a different key order? Supply your own comparator
Comparator<String> descIgnoreCase = Comparator
.comparing(String::toLowerCase)
.reversed();
List<Foo> result = foos.stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(
Foo::getFieldA,
Function.identity(),
(f1, f2) -> f1, // choose winner
() -> new TreeMap<>(descIgnoreCase) // 👈 custom order
),
m -> new ArrayList<>(m.values())
));
Why this works
• Set iteration order is arbitrary, so we must not rely on “encounter order”.
• TreeMap guarantees that once the map is built, its entries are sorted by the given comparator (natural order by default).
• The merge function tells Java which duplicate to keep.
That’s it—deterministic, one-per-fieldA, and always in the same order no matter how the original Set got shuffled. 🚀