2016-07-07 94 views
3

我有這樣排序的日期列表:如何排序地圖<YearMonth,列表<LocalDate>>與Java 8 Lambda和流

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>>與流:

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, ...]} 

我如何排序都是由鍵和值?

回答

3

使用TreeMap作爲收集器,所以輸出按鍵排序。

事情是這樣的:

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

工程完美。謝謝 – Patrick

2

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

您可以使用返回分類收集特定Collectors。 在你的情況我會用一個TreeMap其鍵所產生的地圖進行排序,並將得到的值的集合那樣明確排序:

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

您可以通過以下方式對它們進行排序: -

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())); 
相關問題