Search code examples
javajava-stream

How to group a list of objects into a Map of Map based on object's attributes in Java?


I have a list of objects that I want to convert to a map of maps.

class A {
  String aProp;
  String bProp;
  String cProp;
}

then I have List<A> aList. and I am trying to convert them into a map -

Map<aProp, Map<bProp, cProp>>

how can I achieve this? I tried Collectors.groupingBy but still not able to achieve what I want.


Solution

  • Assuming that the aProp and bProp combinations are unique:

    Map<String, Map<String, String>> map = aList.stream()
            .collect(Collectors.groupingBy(
                    a -> a.aProp,
                    Collectors.toMap(a -> a.bProp, a -> a.cProp)
            ));
    // map ==> {1={2=3}, 2={3=4}, 3={4=5}}
    

    If there are instances with the same values for aProp and bProp, then the toMap collector will cause an exception to be thrown. If that's going to happen you can use one of the other toMap methods. For instance, toMap(a -> a.bProp, a -> a.cProp, (x, y) -> y)) will take the last value (although the order doesn't guarantee what that "last value" will be).