If you just want to iterate through map, can use a TreeSet
to keep the keys, for he will already order them:
Map<Date, List<Exam>> map = ...
// cria um TreeSet, com as chaves ordenadas
SortedSet<Date> keys = new TreeSet<>(map.keySet());
for (Date date : keys) { // percorre as chaves ordenadas e obtém o respectivo valor
setNewList(date, map.get(date));
}
As the class Date
already implements the interface Comparable
, the keys are already inserted in the TreeSet
orderly.
But if you want, you can also create another map, already with the sorted keys. For this, use a TreeMap
:
Map<Date, List<Exam>> map = ... // map com as chaves não-ordenadas
TreeMap<Date, List<Exam>> mapOrdenadoPorChaves = new TreeMap<>(map);
for (Date date : mapOrdenadoPorChaves.keySet()) {
setNewList(date, mapOrdenadoPorChaves.get(date));
}
Another option is to use a List
to store keys, so you can even go through in reverse order, for example:
Map<Date, List<Exam>> map = ... // map com as chaves não-ordenadas
List<Date> chaves = new ArrayList<>(map.keySet());
// ordenar as chaves na ordem inversa
Collections.sort(chaves, Collections.reverseOrder());
for (Date date : chaves) {
setNewList(date, map.get(date));
}
It worked, is there any way I can sort it backwards? Like "Sorteddesc" or something ?
– Ricardo Lucas
@Ricardolucas I updated the answer
– hkotsubo
@Ricardolucas Another way is to instantiate the class of Navigablemap.
– Lucas Palomo