JAVAJDK8List分组的实现和用法
概述
成都网站建设、做网站的关注点不是能为您做些什么网站,而是怎么做网站,有没有做好网站,给创新互联一个展示的机会来证明自己,这并不会花费您太多时间,或许会给您带来新的灵感和惊喜。面向用户友好,注重用户体验,一切以用户为中心。
对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) { ListcouponList = 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 > 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
},
{
"couponId":3,
"name":"优惠券4",
"price":400
}
]
}
如果分组后,分组内并不想是对象,而是对象的属性,也可以做到的。
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 ListGroupTest2 { public static void main(String[] args) { ListcouponList = 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 > 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"
]
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对创新互联的支持。如果你想了解更多相关内容请查看下面相关链接
网站栏目:JAVAJDK8List分组的实现和用法
网页链接:http://myzitong.com/article/pjepod.html