Two things can happen when you say “in order”:
- You want a deterministic, sorted result by
fieldA, no matter what order the input has.
- You just want to keep the encounter order of the stream (the first time you see a key you keep it), but you also want that encounter order preserved in the final collection.
Below are both variants. Pick whichever matches your use-case 👇
1️⃣ Sorted by fieldA (ascending)
List<Foo> distinctSorted =
foos.stream() // any Collection<Foo>
.collect(Collectors.collectingAndThen(
Collectors.toMap(
Foo::getFieldA, // key = fieldA
Function.identity(), // value = the object
(first, ignored) -> first, // keep the first (or change to keep last)
TreeMap::new // 🔑 TreeMap keeps keys sorted
),
map -> new ArrayList<>(map.values()) // turn Map → List
));
• TreeMap orders the keys (here, fieldA) using their natural order.
• Result list is now deterministically sorted by fieldA.
Need a custom order (e.g., case-insensitive, descending, etc.)?
Replace TreeMap::new with
() -> new TreeMap<>(Comparator.comparing(String::toLowerCase).reversed())
2️⃣ Keep encounter order (first-come-first-served)
List<Foo> distinctEncounterOrder =
foos.stream()
// .sorted(...) // ← optional: pre-sort if you want a different “encounter” order
.collect(Collectors.collectingAndThen(
Collectors.toMap(
Foo::getFieldA,
Function.identity(),
(first, ignored) -> first, // keep first; use (a,b)->b for “keep last”
LinkedHashMap::new // 🔑 preserves insertion order
),
map -> new ArrayList<>(map.values())
));
Notes
• Because we use a LinkedHashMap, the order in the resulting list matches the stream’s encounter order.
• If the incoming collection is a Set with unpredictable iteration order, simply sort the stream first (e.g., .sorted(Comparator.comparing(Foo::getFieldA))) and then collect with LinkedHashMap—that gives you both stable ordering and “keep first/last” semantics.
Cheat-sheet 📝
| Goal | Collector Map impl. | Extra step |
|---|
| Sorted by key | TreeMap::new | none |
| Encounter order | LinkedHashMap::new | optionally sorted(..) before collecting |
That’s it! Pick the flavour that matches what you mean by “order”. Happy coding 🚀