繁体   English   中英

如何使用java 8 lambda和streams对Map <YearMonth,List <LocalDate >>进行排序

[英]How to sort Map<YearMonth, List<LocalDate>> with java 8 lambda and streams

我有一个这样的排序日期列表:

2016-07-07
2016-07-08
2016-07-09
2016-07-10
2016-07-11
2016-07-12
2016-07-13
...
2016-07-31
2016-08-01
2016-08-02
2016-08-03
...
2017-01-01
2017-01-02
2017-01-03
...

从这个列表中我生成一个Map<YearMonth, List<LocalDate>> with stream:

Map<YearMonth, List<LocalDate>> d = dates.stream().collect(Collectors.toList())
      .stream().collect(Collectors.groupingBy(date -> YearMonth.from(date)));

该映射的输出如下所示:

{2016-12=[2016-12-01, 2016-12-02,...2016-12-31], 2016-11=[2016-11-01, 2016-11-02,...]}

但我需要的输出应该是这样的:

  • 按日期升序排序的地图键: {2016-07=[...], 2016-08=[...]}
  • 按日期升序排序的地图(列表)的值: {2016-07=[2016-07-01, 2016-07-02, ...], 2016-08=[2016-08-01, 2016-08-02, ...]}

我尝试了很多选项来获得我的预期结果,但我只是得到了正确的键或值的排序, 而不是两者

Map<YearMonth, List<LocalDate>> m = stream().collect(Collectors.toList())
      .stream().sorted((e1,e2) -> e2.compareTo(e1))
      .collect(Collectors.groupingBy(date -> YearMonth.from(date)));

结果:

{2016-07=[2016-07-31, 2016-07-30, ...], 2016-08=[2016-08-31, 2016-08-30, ...]}

如何按键和值对它们进行排序?

使用TreeMap作为收集器,以便按键对输出进行排序。

像这样的东西:

 dates.stream()
      .sorted()
      .collect(
         Collectors.groupingBy(YearMonth::from, TreeMap::new, Collectors.toList())
      );

Collectors.groupingBy(date -> YearMonth.from(date))内部将结果存储在HashMap中,并且密钥排序丢失。

此实现将保留键顺序:

  Map<YearMonth, List<LocalDate>> d = dates
        .stream()
        .sorted((e1,e2) -> e2.compareTo(e1))
        .collect(Collectors
                .groupingBy(YearMonth::from,
                        LinkedHashMap::new,
                        Collectors.toList()));

您可以使用返回已排序集合的特定Collectors 在您的情况下,我将使用TreeMap按其键对结果Map进行排序,并显式对结果值集合进行排序:

Map<YearMonth, List<LocalDate>> m = dates.stream()
   .collect(Collectors.groupingBy(
              date -> YearMonth.from(date),
              TreeMap::new,
              Collectors.collectingAndThen(
                Collectors.toList(),
                (list) -> { Collections.sort(list); return list; })));

您可以通过以下方式对它们进行排序: -

Map<YearMonth, List<LocalDate>> map = dates.stream()
        .collect(Collectors.toList())
        .stream()
        .sorted((e1,e2) -> e1.compareTo(e2))
        .collect(Collectors.groupingBy(date -> YearMonth.from(date), TreeMap::new, Collectors.toList()));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM