最近在工作中加大了lambda表达式的使用,特此记录一些,会不断更新。
list转成map,收集实体本身
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
}
list转成map,处理key重复的情况
1)、toMap有个重载方法,可以传入一个合并的函数来解决key冲突问题
下面只是简单的使用后者覆盖前者来解决key重复问题
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
2)、指定具体收集的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));
}
list转map,分组
//List 以ID分组 Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
list转成map,其中model本身做key,list中重复个数为value
Map<String, Long> resultMap = productList.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
过滤map中value的值大于1的键值对
Map<String, Long> tempMap = resultMap.entrySet().stream()
.filter(r -> r.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));