Java8中list转map方法 .stream.collect(Collectors.toMap())

2022-08-01 12:27:45

常用方式

1. 利用Collectors.toMap方法进行转换

publicMap<Long,String>getIdNameMap(List<Account> accounts){return accounts.stream().collect(Collectors.toMap(Account::getId,Account::getUsername));}

其中第一个参数就是key,第二个参数就是value的值。

2. 收集对象实体本身

  • 在开发过程中我们也需要有时候对自己的list中的实体按照其中的一个字段进行分组(比如 id ->List),这时候要设置map的value值是实体本身。
publicMap<Long,Account>getIdAccountMap(List<Account> accounts){return accounts.stream().collect(Collectors.toMap(Account::getId, account-> account));}

account -> account是一个返回本身的lambda表达式,其实还可以使用Function接口中的一个默认方法 Function.identity(),这个方法返回自身对象,更加简洁

3. 重复key的情况

publicMap<String,Account>getNameAccountMap(List<Account> accounts){return accounts.stream().collect(Collectors.toMap(Account::getUsername,Function.identity(),(key1, key2)-> key2));}

在list转为map时,作为key的值有可能重复,这时候流的处理会抛出个异常:Java.lang.IllegalStateException:Duplicate key。这时候就要在toMap方法中指定当key冲突时key的选择。(这里是选择第二个key覆盖第一个key)

4. 用groupingBy 进行分组

publicMap<Long,Account>getIdAccountMap(List<Account> accounts){return accounts.stream().collect(Collectors.groupingBy(Account::getId));}

根据一个字段或者属性分组也可以直接用groupingBy方法,很方便。

5. partitioningBy 进行分组

publicMap<Long,Account>getIdAccountMap(List<Account> accounts){return accounts.stream().collect(Collectors.partitioningBy(Account->Account::getId<100));}

partitioningBy可以理解为特殊的groupingBy,key值为true和false,当然此时方法中的参数为一个判断语句(用于判断的函数式接口)

下表展示 Collectors 类的静态工厂方法。

工厂方法返回类型作用
toListList把流中所有项目收集到一个 List
toSetSet把流中所有项目收集到一个 Set,删除重复项
toCollectionCollection把流中所有项目收集到给定的供应源创建的集合menuStream.collect(toCollection(), ArrayList::new)
countingLong计算流中元素的个数
sumIntInteger对流中项目的一个整数属性求和
averagingIntDouble计算流中项目 Integer 属性的平均值
summarizingIntIntSummaryStatistics收集关于流中项目 Integer 属性的统计值,例如最大、最小、 总和与平均值
joiningString连接对流中每个项目调用 toString 方法所生成的字符串collect(joining(", "))
maxByOptional一个包裹了流中按照给定比较器选出的最大元素的 Optional, 或如果流为空则为 Optional.empty()
minByOptional一个包裹了流中按照给定比较器选出的最小元素的 Optional, 或如果流为空则为 Optional.empty()
reducing归约操作产生的类型从一个作为累加器的初始值开始,利用 BinaryOperator 与流 中的元素逐个结合,从而将流归约为单个值累加int totalCalories = menuStream.collect(reducing(0, Dish::getCalories, Integer::sum));
collectingAndThen转换函数返回的类型包裹另一个收集器,对其结果应用转换函数int howManyDishes = menuStream.collect(collectingAndThen(toList(), List::size))
groupingByMap<K, List>根据项目的一个属性的值对流中的项目作问组,并将属性值作 为结果 Map 的键
partitioningByMap<Boolean,List>根据对流中每个项目应用谓词的结果来对项目进行分区
  • 作者:小胡小胡哪壶不开提哪壶
  • 原文链接:https://blog.csdn.net/tototototoo/article/details/120770250
    更新时间:2022-08-01 12:27:45