Here are several ways. Given two records (classes would also work).
record Pair<T> (T getItem1, T getItem2) {
}
record OtherObject() {}
The first simply establishes a TreeMap
as suggested by Louis Wasserman in the comments. A comparator first compares the first item of the pair, and, if equal, the second item. To resolve object inference issues, the first comparison uses a lambda. The next comparison can then use a method reference.
Comparator<Pair<LocalDate>> comp = Comparator.comparing(
(Pair<LocalDate> p) -> p.getItem1())
.thenComparing(Pair::getItem2);
Now establish the TreeMap
using the comparator.
NavigableMap<Pair<LocalDate>, Pair<OtherObject>> navigableMap = new TreeMap<>(comp);
The second way simply sorts the map entries based on the map key and places them in a list. The first item the comparator is a keyExtractor
, the return type of which is Pair<LocalDate>
used in the comparisons.
List<Entry<Pair<LocalDate>,Pair<OtherObject>>> entryList =
someMap.entrySet().stream().sorted(Comparator.comparing(Entry::getKey,
Comparator.comparing(
(Pair<LocalDate> p) -> p.getItem1())
.thenComparing(Pair::getItem2))).toList();
Note: TreeMap
implements NavigableMap
which extends SortedMap
which extends Map