【发布时间】:2021-01-14 16:19:18
【问题描述】:
我想按列表中的第一个元素进行过滤,并在按第二个元素分组后获得平均值。
public class MyClass{
int index;
String fruit;
int quantity;
public MyClass(int index, String fruit, int quantity){
this.index = index;
this.fruit = fruit;
this.quantity = quantity;
}
public int getIndex(){
return index;
}
public String getFruit(){
return fruit;
}
public int getQuantity(){
return quantity;
}
ArrayList<MyClass> test = new ArrayList<MyClass>();
MyClass t1 = new MyClass(1, "apple", 6);
test.add(t1);
MyClass t2 = new MyClass(2, "apple", 6);
test.add(t2);
MyClass t3 = new MyClass(1, "banana", 6);
test.add(t3);
MyClass t4 = new MyClass(2, "banana", 6);
test.add(t4);
...
Myclass t20 = new MyClass(10, "apple", 6);
if (MyClass.getIndex() <= 5){
Map<String, Integer> map = test.stream()
.collect(groupingBy(MyClass::fruit, averagingLong(MyClass::quantity)));
}
//desired return
// {apple: 12, banana:12}
}
在使用 Java Stream 获得平均值之前,我正在过滤第一个索引元素。这是正确的方法吗?
【问题讨论】:
-
MyClass中没有方法fruit和quantity可用作方法引用,请使用现有的 getter(或重命名它们)。
标签: java