1. 程式人生 > >JDK 8 list分組獲取第一個元素

JDK 8 list分組獲取第一個元素

概述


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
	}
}