List转Map

本文介绍了Java8StreamAPI的几种常见用法,如list转map避免键冲突、提取对象属性、按ID分组、计算最大值/最小值以及初始化数组。展示了如何使用toMap、groupingBy、max/min和summarizingInt等方法进行数据处理。
摘要由CSDN通过智能技术生成

一、list转map

Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));

看来还是使用JDK 1.8方便一些。

二、另外,转换成map的时候,可能出现key一样的情况,如果不指定一个覆盖规则,上面的代码是会报错的。转成map的时候,最好使用下面的方式:
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));

三、有时候,希望得到的map的值不是对象,而是对象的某个属性,那么可以用下面的方式:
Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));

四、List转Map<List<>>

List 以ID分组 Map<Integer,List>
Map<Integer, List> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));

五、stream 对象列表取最大值

Person person = personList5.stream().max((p1, p2) -> p1.getAge() - p2.getAge()).get();

六、同时计算最大值、最小值

Collectors.summarizingInt()实现

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2));
IntSummaryStatistics intSummaryStatistics = list.stream().collect(Collectors.summarizingInt(x -> x));
Integer max = intSummaryStatistics.getMax();
Integer min = intSummaryStatistics.getMin();

七、使用 Arrays.fill() 方法初始化数组

int[] myArray = new int[10];

Arrays.fill(myArray, 0);

参考:

https://blog.csdn.net/m0_67266787/article/details/123981453

stream 取最大对象、取最大值_stream取最大值_水脏的博客-CSDN博客Java8中Stream流求最大值最小值怎么实现-PHP博客-李雷博客

如何在 Java 中将所有数组元素初始化为零-火焰兔

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小田田_XOW

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值