简体   繁体   English

使用lambda表达式创建嵌套的哈希图

[英]create nested hashmap using lambda expression

I want to create three layer HashMap using lambda expressions from an input ArrayList in Java. 我想使用Java中的输入ArrayList使用lambda表达式创建三层HashMap The three layers are year, month and week, and here is my code for first two layers. 这三层分别是年,月和周,这是我前两层的代码。 However, in the second layer I am getting an error (first layer works fine). 但是,在第二层中,我遇到了一个错误(第一层工作正常)。

public HashMap<Integer,HashMap<Integer,HashMap<Integer,AbcDetails>>> createHashMapOfTimePeriod(List<AbcDetails> abcDetails){

    Map<Integer,List<AbcDetails>>result1=abcDetails.stream().collect(Collectors.groupingBy(AbcDetails::getYear));
    Map<Integer,Map<Integer,AbcDetails>>reult2=result1.entrySet().stream().collect(Collectors.groupingBy(e -> (e.getValue().stream().collect(Collectors.groupingBy(AbcDetails::getWeek)))));

    return null;

}

You can achieve this with nested Collector s: 您可以使用嵌套的Collector实现此目的:

Map<Integer,Map<Integer,Map<Integer,AbcDetails>>> groups = 
  abcDetails.stream ()
        .collect(Collectors.groupingBy (AbcDetails::getYear,
                                        Collectors.groupingBy (AbcDetails::getMonth,
                                                               Collectors.toMap (AbcDetails::getWeek, Function.identity()))));

Note that if there may be multiple AbcDetails instances having the same year, month and week, the inner Map will have multiple values for the same key, so the above code will fail. 请注意,如果可能有多个具有相同年,月和周的AbcDetails实例,则内部Map将为同一键具有多个值,因此上述代码将失败。 One way to resolve such a problem is to change your output to: 解决此问题的一种方法是将输出更改为:

Map<Integer,Map<Integer,Map<Integer,List<AbcDetails>>>> groups = 
  abcDetails.stream ()
        .collect(Collectors.groupingBy (AbcDetails::getYear,
                                        Collectors.groupingBy (AbcDetails::getMonth,
                                                               Collectors.groupingBy (AbcDetails::getWeek))));

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

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