public class Test { /*** * 使用java代码 将下列界面中的数据进行合并,必须定义初始数据的存储类型,必须定义结果集的数据类型,写出实现合并的逻辑过程 * NUM QTY */ public static void main(String[] args) { //初始化数据 ArrayList<Result> list = new ArrayList<>(); list.add(new Result(1,3)); list.add(new Result(3,4)); list.add(new Result(2,5)); list.add(new Result(1,6)); list.add(new Result(4,7)); list.add(new Result(3,8)); list.add(new Result(2,9)); //返回结果 ArrayList<Result> reList = new ArrayList<>(); //相同NUM 合并过程 list.stream().collect(Collectors.groupingBy(e->e.getNUM())).forEach((k,v)->{ int sum = v.stream().mapToInt(Result::getQTY).sum(); v.get(0).setQTY(sum); reList.add(v.get(0)); });
//结果[Result(NUM=1, QTY=9), Result(NUM=2, QTY=14), Result(NUM=3, QTY=12), Result(NUM=4, QTY=7)] System.out.println(reList); } } @Data @NoArgsConstructor @AllArgsConstructor class Result{ private Integer NUM; private Integer QTY; }