2

I want to create three layer HashMap using lambda expressions from an input ArrayList in Java. 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;

}

1 Answer 1

5

You can achieve this with nested 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()))));

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. 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))));
Sign up to request clarification or add additional context in comments.

2 Comments

but in second and third layer data is repeating only year is unique is that works here?
@shridhar The only issue may be with the inner most map. If there are multiple objects having the same year, month and week, you would have a duplicate key in the inner most map and must decide how to resolve it. You can change the structure to Map<Integer,Map<Integer,Map<Integer,List<AbcDetails>>>> to account for such duplicate keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.