Search code examples
javalistdictionaryjava-streamcollectors

How can I map the elements of the Lists created by the Collectors.groupingby collector to an other type using streams?


I have a stream of objects with multiple attributes and I want to create a Map of two of the Attributes of these objects.

For example:

class MyClass
{
   private int A;
   private int B;
   private String C;

   //constructor, getters, setters, etc...
}

using Collectors.groupingBy(), I can create a Map< String, List< MyClass>>:

Map<String, List<Myclass>> = inputStream.collect(Collectors.groupingby(MyClass::getC));

but I want to have a Map< String, List< int>> with Myclass.C as key and MyClass.B as list elements.
MyClass.A should not be contained in the result.
How can I do this?

Thanks in advance


Solution

  • inputStream.collect(
      Collectors.groupingBy(
        MyClass::getC,
        Collectors.mapping(
          MyClass::getB,
          Collectors.toList())));