Java 8 GroupingBy with Object Collectors

I would like to pass a stream of objects myClassto group using Collectors.groupingBy(). But instead of retrieving Map<String, List<myClass>>, I would like to group it by object myOutputand get Map<String, myOutput>. I tried to create a custom collector:

List<myClass> myList = new ArrayList<myClass>();
myList.add(new myClass("a", 1));
myList.add(new myClass("a", 2));
myList.add(new myClass("b", 3));
myList.add(new myClass("b", 4));

Map<String,myOutput> myMap = myList.stream().collect(Collectors.groupingBy(myClass::getA, Collectors.of(myOutput::new, myOutput::accept, myOutput::combine)));

myClass:

protected String a;
protected int b;

public myClass(String aA, int aB)
{
  a = aA;
  b = aB;
}

public String getA()
{
  return a;
}

public int getB()
{
  return b;
}

myOutput:

protected int i;

public myOutput()
{
  i = 0;
}

public void accept(myClass aMyClass)
{
  i += aMyClass.getB();
}

public myOutput combine(myOutput aMyOutput)
{
  i += aMyOutput.getI();
  return this;
}

public int getI()
{
  return i;
}

But with this code there is a problem with the collector:

Collectors.of(myOutput::new, myOutput::accept, myOutput::combine)

I know that in this case, the reduction will be much easier, but let it be assumed that there are many operations in the myOutput object.

What happened to this collector?

+4
source share
1 answer

. Collector.of static factory ( Collectors.of).

    Map<String,myOutput> myMap = 
        myList.stream()
              .collect(Collectors.groupingBy(
                myClass::getA, 
                Collector.of(myOutput::new, myOutput::accept, myOutput::combine)
              ));

, , . . a , a, b. Collectors.summingInt(mapper), mapper b:

Map<String,Integer> myMap = 
    myList.stream()
          .collect(Collectors.groupingBy(
            myClass::getA, 
            Collectors.summingInt(myClass::getB)
          ));
+6

All Articles