按 LocalDateTime 对流中的地图进行排序

Sort map in stream by LocalDateTime

我有地图Map<LocalDateTime, String>

如何按键值排序?我应该使用什么比较器?

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

someMap.entrySet().stream().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

没有排序:

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

您可以这样使用 .sorted(Map.Entry.comparingByKey())

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));

输出

{2020-04-01T12:27:48.054=info, 2020-04-17T11:15:13.423=info, 2020-04-29T11:01:21.372=info}
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);
});

将导致

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