JDK8的lambda方式List转Map的操作方法
作者:诸葛小猿
account是一个返回本身的lambda表达式,其实还可以使用Function接口中的一个默认方法代替,使整个方法更简洁优雅,这篇文章主要介绍了JDK8的lambda方式List转Map,需要的朋友可以参考下
JDK8的lambda方式List转Map
遍历
public void forEach(Map<Long, String> map) {
map.forEach((k, v) -> {
System.out.println("k=" + k + ",v=" + v);
});
}list转map
代码如下:
public Map<Long, String> getIdNameMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}list转成实体本身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()));
}list转map:重复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重复问题。
举例:
List<TDeliveryOperation> tDeliveryOperations = tDeliveryOperationMapper.selectList(wrapper1);
Map<Long, TDeliveryOperation> operationMap = tDeliveryOperations.stream()
.collect(Collectors.toMap(
TDeliveryOperation::getOrderId,
Function.identity(),
(key1, key2) -> {
// 如果存在多条记录 选择最后更新时间最大的
if (key1.getLastUpdatedAt() != null
&& key2.getLastUpdatedAt() != null
&& key1.getLastUpdatedAt().getTime() >= key2.getLastUpdatedAt().getTime()) {
return key1;
}
return key2;
})
);指定具体收集的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));
}到此这篇关于JDK8的lambda方式List转Map的文章就介绍到这了,更多相关JDK8 List转Map内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
