java8将list转为map及Collectors groupingBy

mac2025-07-15  2

List集合的stream().collect()方法

Map<Byte, List<String>> levelList = bottles.stream().collect(

Collectors.groupingBy(

ProductBottle::getLevel, Collectors.mapping(ProductBottle::getQrcode, Collectors.toList())

));

List.stream().collect(Collectors的一系列方法)

java8 新特性学习 转自 http://ifeve.com/stream/ 

其次是map,我们知道map的key是不能重复的,所以groupingBy就针对于相同key值做了处理:转自https://blog.csdn.net/Hatsune_Miku_/article/details/73414406 

结果为以level分组的map集合

使用java8的lambda将list转为map:转自  https://www.cnblogs.com/xujanus/p/6133865.html

出自:https://blog.csdn.net/qq_34638435/article/details/80076878

------------------------------下面是对这些知识点的一个汇总------------------------------------

 

先理解下lambda表达式

lambda:一段带有输入参数的可执行语句块

lambda表达式的一般语法:

(Type1 param1, Type2 param2, ..., TypeN paramN) -> {

      statment1;

      statment2;

     //.............

      return statmentM;

    }

 

 

参数类型省略–绝大多数情况,编译器都可以从上下文环境中推断出lambda表达式的参数类型。这样lambda表达式就变成了:

(param1,param2, ..., paramN) -> {

  statment1;

  statment2;

  //.............

  return statmentM;

}

当lambda表达式的参数个数只有一个,可以省略小括号。lambda表达式简写为:

param1 -> {

  statment1;

  statment2;

  //.............

  return statmentM;

}

 

当lambda表达式只包含一条语句时,可以省略大括号、return和语句结尾的分号。lambda表达式简化为:

param1 -> statment

 

使用java8将list转为map

了解lambda:Java8初体验(一)lambda表达式语法

了解stream:Java8初体验(二)Stream语法详解

常用方式

代码如下:

public Map<Long, String> getIdNameMap(List<Account> accounts) {

return accounts.stream().collect(

Collectors.toMap(Account::getId, Account::getUsername)

);

}

收集成实体本身map

代码如下:

public Map<Long, Account> getIdAccountMap(List<Account> accounts) {

return accounts.stream().collect(

Collectors.toMap(Account::getId, account -> account)

);

}

account -> account是一个返回本身的lambda表达式,其实还可以使用Function接口中的一个默认方法代替,使整个方法更简洁优雅:

 

public Map<Long, Account> getIdAccountMap(List<Account> accounts) {

return accounts.stream().collect(

Collectors.toMap(Account::getId, Function.identity())

);

}

重复key的情况

代码如下:

 

public Map<String, Account> getNameAccountMap(List<Account> accounts) {

return accounts.stream().collect(

Collectors.toMap(Account::getUsername, Function.identity())

);

}

这个方法可能报错(java.lang.IllegalStateException: Duplicate key),因为name是有可能重复的。toMap有个重载方法,可以传入一个合并的函数来解决key冲突问题:

 

public Map<String, Account> getNameAccountMap(List<Account> accounts) {

return accounts.stream().collect(

Collectors.toMap(

Account::getUsername, Function.identity(), (key1, key2) -> key2

)

);

}

这里只是简单的使用后者覆盖前者来解决key重复问题。

指定具体收集的map

toMap还有另一个重载方法,可以指定一个Map的具体实现,来收集数据:

public Map<String, Account> getNameAccountMap(List<Account> accounts){

return accounts.stream().collect(

Collectors.toMap(

Account::getUsername, Function.identity(), (key1, key2) ->

key2,LinkedHashMap::new)

);

}

最新回复(0)