JDK 8 lambda常用集合方法
2020-05-20 本文已影响0人
else05
1. 常见方法
public Map<Long, String> getIdNameMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}
2. 收集成实体本身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()));
}
3. 重复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冲突问题: 这里只是简单的使用后者覆盖前者来解决key重复问题。
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
4. 取出对象list中的属性成新的list , 要注意空指向的问题
list.stream().map(User::getMessage).collect(Collectors.toList())
5 . 简单如重
list.stream().distinct().collect(Collectors.toList());
6 .分组求和
// 通过userName进行分组,并把用户的score进行求和
Map<String, Integer> invCountMap = list.stream().collect(Collectors.groupingBy(User::getName, Collectors.summingInt(User::getScore)));
// 通过userName进行分组,然后统计出每个userName的数量
Map<String, Integer> invCountMap = list.stream().flatMap(Collection::stream).collect(Collectors.groupingBy(User::getName, Collectors.counting()));
7 .自定义集合类型
- 线程安全的set
list.stream().map(User:getName).collect( Collectors.toCollection(() -> Collections.newSetFromMap(new ConcurrentHashMap<>())));
- 自定义Collection
list.stream().map(User:getName).collect(Collectors.toCollection(LinkedList::new));
Map<String, List<List<String>>> map2 = conditions.stream().collect(Collectors.groupingBy(Condition::getCondName, Collectors.mapping(Condition::getCondValue, Collectors.toList())));
- 自定义Map
Map<String,User> = list.stream().collect(Collectors.toMap(User:getName,Function.identity(),(k1,k2)->k2,LinkedHashMap::new));
Map<Integer, List<Student>> studentMap = students.stream().collect(Collectors.groupingBy(Student::getAge, LinkedHashMap::new, Collectors.toList()));