JAVA JDK8 List分组的实现和用法分组的实现和用法
今天小编就为大家分享一篇关于JAVA JDK8 List分组的实现和用法,小编觉得内容挺不错的,现在分享给大家,具有很好的参
考价值,需要的朋友一起跟随小编来看看吧
概述概述
对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 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;
}
}
上面的例子是对List按照couponId分组,couponId一样的,归为一组。打印结果如下:
{
1:[
{
"couponId":1,
"name":"优惠券1",
"price":100
}
],
2:[
{
"couponId":2,
"name":"优惠券2",
"price":200
}
],
3:[
{
"couponId":3,
"name":"优惠券3",
"price":300
},