JDK 8 list分组获取第一个元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linsongbin1/article/details/84112877

概述


JDK8 List分组一文中介绍了JDK 8如何对list进行分组,但是没有提到如何在分组后,获取每个分组的第一个元素。其实这个也很简单,代码如下:

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 ListGroupFindFirstTest3 {
    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, Coupon> resultList = couponList.stream().collect(Collectors.groupingBy(Coupon::getCouponId,Collectors.collectingAndThen(Collectors.toList(),value->value.get(0))));
        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;
    }
}

需要借助Collectors.collectingAndThen方法,对组内的元素进行处理,这里是获取第一个元素。

代码输出结果如下:

{   1:{
		"couponId":1,
		"name":"优惠券1",
		"price":100
	},
	2:{
		"couponId":2,
		"name":"优惠券2",
		"price":200
	},
	3:{
		"couponId":3,
		"name":"优惠券3",
		"price":300
	}
}

猜你喜欢

转载自blog.csdn.net/linsongbin1/article/details/84112877