【问题标题】:Filter by first element from Java List按 Java List 中的第一个元素过滤
【发布时间】: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 中没有方法 fruitquantity 可用作方法引用,请使用现有的 getter(或重命名它们)。

标签: java


【解决方案1】:

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

//想要的回报
// {苹果: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}

【讨论】:

    【解决方案2】:

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

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

    您可能还需要将 ArrayList 测试中的代码封装在一个方法中

    【讨论】:

    • 感谢您的回答。顺便说一句,你知道我为什么会得到这个吗? “方法 averagingInt(MyClass::getQuantity) 未定义 MyClass 类型”
    • @BryanK。可能您缺少 Collectors.averagingInt 的静态导入
    猜你喜欢
    • 2015-10-25
    • 2020-12-18
    • 2023-04-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多