1

I just want to know how I can sort by chnrological order a Map<LocalDate, Integer>.

Here's the first line of my code :

Map<LocalDate, Integer> commitsPerDate = new HashMap<>();

Afterwards, I fill in my Map with any value (but not in chronological order). And when I display the values of my Map, it is displayed in this order :

for(var item : commitsPerDate.entrySet()) {
     System.out.println(item.getKey() + " = " + item.getValue());
}
2020-08-31 = 1
2020-09-30 = 3
2020-09-29 = 1
2020-09-28 = 5
2020-09-27 = 5
2020-08-27 = 4
2020-09-25 = 3
2020-10-21 = 1
2020-10-18 = 1
2020-10-17 = 5
2020-10-16 = 4
2020-10-15 = 5
2020-10-14 = 6
2020-09-14 = 1
2020-10-13 = 2
2020-09-13 = 2

And I would like it to be sorted in chronological order so that the display is in the same order.

Thank you.

Elody T.
  • 31
  • 3

1 Answers1

2

As Pshemo has already mentioned, if you want the map to order elements by key then you can use TreeMap instead of HashMap.

Demo:

import java.time.LocalDate;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<LocalDate, Integer> commitsPerDate = new TreeMap<>();
        commitsPerDate.put(LocalDate.parse("2020-08-31"), 1);
        commitsPerDate.put(LocalDate.parse("2020-09-30"), 3);
        commitsPerDate.put(LocalDate.parse("2020-09-29"), 1);
        commitsPerDate.put(LocalDate.parse("2020-09-28"), 5);

        System.out.println(commitsPerDate);
    }
}

Output:

{2020-08-31=1, 2020-09-28=5, 2020-09-29=1, 2020-09-30=3}

In the reverse order:

import java.time.LocalDate;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<LocalDate, Integer> commitsPerDate = new TreeMap<>(Collections.reverseOrder());
        commitsPerDate.put(LocalDate.parse("2020-08-31"), 1);
        commitsPerDate.put(LocalDate.parse("2020-09-30"), 3);
        commitsPerDate.put(LocalDate.parse("2020-09-29"), 1);
        commitsPerDate.put(LocalDate.parse("2020-09-28"), 5);

        System.out.println(commitsPerDate);
    }
}

Output:

{2020-09-30=3, 2020-09-29=1, 2020-09-28=5, 2020-08-31=1}

For any reason, if you have to use HashMap, check How to sort Map values by key in Java?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110