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

shr*_*har 2 java collections lambda hashmap java-8

我想HashMap使用来自ArrayListJava输入的 lambda 表达式创建三层。三层是年、月和周,这是我的前两层代码。但是,在第二层我收到一个错误(第一层工作正常)。

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;

}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 5

您可以使用嵌套的Collectors来实现这一点:

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()))));
Run Code Online (Sandbox Code Playgroud)

请注意,如果可能有多个AbcDetails实例具有相同的年、月和周,则内部Map将具有相同键的多个值,因此上述代码将失败。解决此类问题的一种方法是将输出更改为:

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