代码之家  ›  专栏  ›  技术社区  ›  michele

Java查询预定义对象的ArrayList

  •  1
  • michele  · 技术社区  · 7 年前

    我有一个ArrayList(inputList)来解析这些数据:

    id,name,quantity
    1,foo,10
    2,bar,20
    3,foo,10
    4,bar,10
    5,qwerty,1
    

    代码:

    ...
    List<FooRow> inputList = new ArrayList<FooRow>();
    inputList = br.lines().map(mapToFooRow).collect(Collectors.toList());
    ...
    
    public class FooRow{
    private Integer id;
    private String name;
    private Integer value;
    }
    

    name,value
    foo,20
    bar,30
    qwerty,1
    

    如何在lambda表达式中创建类收集器来执行此操作? 谢谢。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Oleksandr Pyrohov Andreas    7 年前

    你可以用 Collectors.groupingBy Collectors.summingInt

    Map<String, Integer> result =
        inputList.stream()
                 .collect(Collectors.groupingBy(
                     FooRow::getName, Collectors.summingInt(FooRow::getValue)));