Bootstrap

java list 分组求和 java8

public static void main(String[] args) {
		List<Car> listOld = new ArrayList<>();
		Car car1 = new Car();
		car1.setNum(1);
		car1.setName("A");
		car1.setColor("红");
		car1.setType(0);
		Car car2 = new Car();
		car2.setNum(1);
		car2.setName("B");
		car2.setColor("黄");
		car2.setType(0);
		Car car3 = new Car();
		car3.setNum(1);
		car3.setName("C");
		car3.setColor("蓝");
		car3.setType(0);
		Car car4 = new Car();
		car4.setNum(1);
		car4.setName("A");
		car4.setColor("红");
		car4.setType(0);
		Car car5 = new Car();
		car5.setNum(1);
		car5.setName("A");
		car5.setColor("红");
		car5.setType(1);
		listOld.add(car1);
		listOld.add(car2);
		listOld.add(car3);
		listOld.add(car4);
		listOld.add(car5);

		List<Car> listNew = new ArrayList<>();
		//筛选分组
		Map<String, List<Car>> map = listOld.stream().filter(o->o.getType().equals(0)).collect(Collectors.groupingBy(o -> o.getName() + o.getColor()));
		//求和
		for (Map.Entry<String, List<Car>> entry : map.entrySet()) {
			Car item = new Car();
			BeanUtils.copyProperties(entry.getValue().get(0),item);
			Integer a = item.getNum() == null ? 0 : item.getNum();
			int i = 0;
			for (Car car : entry.getValue()) {
				if (i > 0) {
					Integer a1 = car.getNum() == null ? 0 : car.getNum();
					a += a1;
				}
				i++;
			}
			item.setNum(a);
			listNew.add(item);
		}
		//筛选求和分组之前
		System.out.println(JSON.toJSON(listOld));
		//筛选求和分组之后
		System.out.println(JSON.toJSON(listNew));
	}

分组以前

[
    {
        "color":"红",
        "num":1,
        "name":"A",
        "type":0
    },
    {
        "color":"黄",
        "num":1,
        "name":"B",
        "type":0
    },
    {
        "color":"蓝",
        "num":1,
        "name":"C",
        "type":0
    },
    {
        "color":"红",
        "num":1,
        "name":"A",
        "type":0
    },
    {
        "color":"红",
        "num":1,
        "name":"A",
        "type":1
    }
]

分组求和之后

[
    {
        "color":"红",
        "num":3,
        "name":"A",
        "type":0
    },
    {
        "color":"黄",
        "num":1,
        "name":"B",
        "type":0
    },
    {
        "color":"蓝",
        "num":1,
        "name":"C",
        "type":0
    }
]

测试用到的实体

package com.gw.service.outbound.entity;

import lombok.Data;

/**
 * @author by lxy
 * @date 2020-07-11 09:38
 */
@Data
public class Car {
	private String name;
	private Integer num;
	private String color;
	private Integer type;
}
;