按Java列表中的第一个元素进行筛选



我想按列表中的第一个元素进行筛选,并在按第二个元素分组后获得平均值。

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}
}

在使用JavaStream获得平均值之前,我正在过滤第一个元素,它是索引。这样做合适吗?

你说的是平均值,但你的问题显示如下:

//所需返回
//{苹果:12,香蕉:12}

要提供所需的回报,您需要执行summingInt,而不是averagingInt

Map<String, Integer> map = test.stream().filter(t->t.getIndex()<=5)
.collect(Collectors.groupingBy(MyClass::getFruit,
Collectors.summingInt(MyClass::getQuantity)));

System.out.println(map);

打印

{banana=12, apple=12}

要按索引进行过滤,可以在流条件后添加过滤谓词,如下所示

Map<String, Double> map = test.stream().filter(m -> m.getIndex() <= 5)
.collect(Collectors.groupingBy(MyClass::getFruit, Collectors.averagingInt(MyClass::getQuantity)));

此外,您可能需要将ArrayList测试中的代码封装在方法中

最新更新