How to sort a Map by key in Java
I am trying to use a loop to show the grouped information of a Map
.
for(Map.Entry<Date, List<Exam>> entry : groupedList.entrySet()) {
setNewList(entry.getKey(), entry.getValue());
}
But it is not ordered, my key
is of type Date
and my values are a List<Classe>
.
Would you like to know how I can sort my Map
by your key
?
Obs: my minSdkVersion is 23.
2 answers
If you just want to iterate through the map, you can use a TreeSet
to save the Keys, as 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 into TreeSet
in an orderly manner.
But if you want, you can also create another map, already with the ordered 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 save the keys, you can even scroll 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));
}
Using Java 8 this could be solved as follows:
public static void main(String[] args) {
Map<Date, Integer> map = new HashMap<>();
map.put(LocalDate.now().toDate(), 1);
map.put(LocalDate.now().plusDays(5).toDate(), 2);
map.put(LocalDate.now().minusDays(10).toDate(), 3);
map.put(LocalDate.now().plusDays(1).toDate(), 4);
LinkedHashMap<Date, Integer> orderedMap = map.entrySet() //
.stream() //
.sorted(Map.Entry.comparingByKey()) //
.collect(Collectors.toMap(Map.Entry::getKey, //
Map.Entry::getValue, //
(key, content) -> content, //
LinkedHashMap::new)); //
System.out.println(orderedMap);
}
The output would be sorting by date:
{Mon Jul 01 00:00:00 BRT 2019=3, Thu Jul 11 00:00:00 BRT 2019=1, Fri Jul 12 00:00:00 BRT 2019=4, Tue Jul 16 00:00:00 BRT 2019=2}