Java8中对List对象集合按照对象中的某个属性进行分组

分类:计算机 | Java | 集合 117
更新:2021-03-23 19:45:38
编辑

参考资料

https://blog.csdn.net/linsongbin1/article/details/83933703

示例

package test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ListGroupTest {
    public static void main(String[] args) {
        List<Coupon> couponList = new ArrayList<>();
        Coupon coupon1 = new Coupon(1,100,"优惠券1");
        Coupon coupon2 = new Coupon(2,200,"优惠券2");
        Coupon coupon3 = new Coupon(3,300,"优惠券3");
        Coupon coupon4 = new Coupon(3,400,"优惠券4");
        couponList.add(coupon1);
        couponList.add(coupon2);
        couponList.add(coupon3);
        couponList.add(coupon4);

        Map<Integer, List<Coupon>> resultList = couponList.stream().collect(Collectors.groupingBy(Coupon::getCouponId));
        System.out.println(JSON.toJSONString(resultList, SerializerFeature.PrettyFormat));
    }
}
package test;

public class Coupon {
    private Integer couponId;
    private Integer price;
    private String name;

    public Coupon(Integer couponId, Integer price, String name) {
        this.couponId = couponId;
        this.price = price;
        this.name = name;
    }

    public Integer getCouponId() {
        return couponId;
    }

    public void setCouponId(Integer couponId) {
        this.couponId = couponId;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

注意事项

Map中key键的数据类型要和进行分组的那个属性(Coupon::getCouponId)数据类型保持一致,否则会报数据类型不一致的错误。