List转Map

一、list转map

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

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

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

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

四、List转Map>

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

五、stream 对象列表取最大值

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

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

Collectors.summarizingInt()实现

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

参考:

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

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

你可能感兴趣的:(java编程,list,windows,数据结构)