1

I have map Map<LocalDateTime, String>.

How can I sort it by key values? What comparator should I use?

someMap.entrySet().stream().sorted(Comparator.comparing(???))

or

someMap.entrySet().stream().sorted(??)

How can I resolve it? What should I write instead "??" ?

Sorted:

Key                      Value
2020-01-09 09:57:58.631  Some info
2020-01-09 09:57:59.224  Some info
2020-01-09 09:59:03.144  Info

Without sorting:

Key                     Value
2020-01-09 09:57:58.631  Some info
2020-01-09 09:59:03.144  Info
2020-01-09 09:57:59.224  Some info
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • Can you show an example of an unsorted `Map`, and the sorted version of the same map? – Sweeper Nov 10 '20 at 10:36
  • @Hulk what should I specify in compareTo method ? –  Nov 10 '20 at 10:42
  • Your example is confusing. You should show the _same_ map both sorted and unsorted. Also, show which of date or string should have a higher priority. Do you sort by the dates first, and if the dates are the same, sort by the strings? Or, do you sort by the strings first, and if the strings are the same, sort by the dates? – Sweeper Nov 10 '20 at 10:44
  • @Sweeper No, I need sort only by dates –  Nov 10 '20 at 10:48

2 Answers2

5

You can use .sorted(Map.Entry.comparingByKey()) like this:

Map<LocalDateTime, String> collect = someMap.entrySet().stream()
        .sorted(Map.Entry.comparingByKey())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o1, o2) -> o1, LinkedHashMap::new));

Output

{2020-04-01T12:27:48.054=info, 2020-04-17T11:15:13.423=info, 2020-04-29T11:01:21.372=info}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1
Map<LocalDateTime, String> map = new HashMap<>();
map.put(LocalDateTime.of(2020, 4, 17, 11, 15), "Value A");
map.put(LocalDateTime.of(2020, 4, 1, 12, 27), "Value B");
map.put(LocalDateTime.of(2020, 4, 29, 11, 1), "Value C");
    
map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> {
    System.out.println(entry);
});

will result in

2020-04-01T12:27=Value B
2020-04-17T11:15=Value A
2020-04-29T11:01=Value C
Mick
  • 954
  • 7
  • 17