JAVA JDK8 List分组获取第一个元素的方法

2025-05-29 0 101

概述

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22
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));

}

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对快网idc的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/linsongbin1/article/details/84112877

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 JAVA JDK8 List分组获取第一个元素的方法 https://www.kuaiidc.com/110775.html

相关文章

发表评论
暂无评论