How to sort a Map by key in Java

Asked

Viewed 1,661 times

2

I’m 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 ain’t ordered, baby key is the type Date and my values are a List<Classe>.

I wonder how I can order mine Map for his key?

Obs: my minSdkVersion is 23.

2 answers

3


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 ?

  • @Ricardolucas I updated the answer

  • @Ricardolucas Another way is to instantiate the class of Navigablemap.

2

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 sort 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}
  • My application has a min SDK in API 23 .stream() doesn’t exist yet.

  • Soon put another example without Java 8 :)

  • Which version did you test with? I tested in Java 8 and LocalDate (package java.time) has not the method toDate(). Actually you didn’t mistake it for the Joda-Time (that has a class with the same name, and this yes has the method toDate)?

  • @hkotsubo, I believe yes, coming home I upgrade to the right :) well observed!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.