JAVA JDK8 List分组的实现和用法
概述
对List进行分组是日常开发中,经常遇到的,在JDK8中对List按照某个属性分组的代码,超级简单。
packagetest; importcom.alibaba.fastjson.JSON; importcom.alibaba.fastjson.serializer.SerializerFeature; importjava.util.ArrayList; importjava.util.List; importjava.util.Map; importjava.util.stream.Collectors; publicclassListGroupTest{ publicstaticvoidmain(String[]args){ ListcouponList=newArrayList<>(); Couponcoupon1=newCoupon(1,100,"优惠券1"); Couponcoupon2=newCoupon(2,200,"优惠券2"); Couponcoupon3=newCoupon(3,300,"优惠券3"); Couponcoupon4=newCoupon(3,400,"优惠券4"); couponList.add(coupon1); couponList.add(coupon2); couponList.add(coupon3); couponList.add(coupon4); Map >resultList=couponList.stream().collect(Collectors.groupingBy(Coupon::getCouponId)); System.out.println(JSON.toJSONString(resultList,SerializerFeature.PrettyFormat)); } }
packagetest; publicclassCoupon{ privateIntegercouponId; privateIntegerprice; privateStringname; publicCoupon(IntegercouponId,Integerprice,Stringname){ this.couponId=couponId; this.price=price; this.name=name; } publicIntegergetCouponId(){ returncouponId; } publicvoidsetCouponId(IntegercouponId){ this.couponId=couponId; } publicIntegergetPrice(){ returnprice; } publicvoidsetPrice(Integerprice){ this.price=price; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ 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
},
{
"couponId":3,
"name":"优惠券4",
"price":400
}
]
}
如果分组后,分组内并不想是对象,而是对象的属性,也可以做到的。
packagetest; importcom.alibaba.fastjson.JSON; importcom.alibaba.fastjson.serializer.SerializerFeature; importjava.util.ArrayList; importjava.util.List; importjava.util.Map; importjava.util.stream.Collectors; publicclassListGroupTest2{ publicstaticvoidmain(String[]args){ ListcouponList=newArrayList<>(); Couponcoupon1=newCoupon(1,100,"优惠券1"); Couponcoupon2=newCoupon(2,200,"优惠券2"); Couponcoupon3=newCoupon(3,300,"优惠券3"); Couponcoupon4=newCoupon(3,400,"优惠券4"); couponList.add(coupon1); couponList.add(coupon2); couponList.add(coupon3); couponList.add(coupon4); Map >resultList=couponList.stream().collect(Collectors.groupingBy(Coupon::getCouponId,Collectors.mapping(Coupon::getName,Collectors.toList()))); System.out.println(JSON.toJSONString(resultList,SerializerFeature.PrettyFormat)); } }
这样分组内就是name属性了。打印结果如下:
{
1:[
"优惠券1"
],
2:[
"优惠券2"
],
3:[
"优惠券3",
"优惠券4"
]
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接