我想流式传输对象集合 myClass
为了使用 Collectors.groupingBy()
对其进行分组.但是,不是检索 Map<String, List<myClass>>
, 我想把它分组在一个对象上 myOutput
并检索 Map<String, myOutput>
.我试图创建一个自定义收集器:
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)));
我的类(class):
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;
}
我的输出:
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;
}
但是对于这段代码,收集器有问题:
Collectors.of(myOutput::new, myOutput::accept, myOutput::combine)
我知道在这种情况下减少会容易得多,但我们假设在 myOutput 对象中有很多操作要做。
这个收集器有什么问题?
最佳答案
你的 Collection 家很好。你只需要有 Collector.of
静态工厂(而不是 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)
映射器返回 b
值的位置:
Map<String,Integer> myMap =
myList.stream()
.collect(Collectors.groupingBy(
myClass::getA,
Collectors.summingInt(myClass::getB)
));
关于对象上带有收集器的 Java 8 GroupingBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36158247/