1. 常見(jiàn)方法
public Map<Long, String> getIdNameMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}
2. 收集成實(shí)體本身map
代碼如下:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}
account -> account是一個(gè)返回本身的lambda表達(dá)式,其實(shí)還可以使用Function接口中的一個(gè)默認(rèn)方法代替豆混,使整個(gè)方法更簡(jiǎn)潔優(yōu)雅:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
}
3. 重復(fù)key的情況
代碼如下:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity()));
}
這個(gè)方法可能報(bào)錯(cuò)(java.lang.IllegalStateException: Duplicate key)送巡,因?yàn)閚ame是有可能重復(fù)的擂找。toMap有個(gè)重載方法,可以傳入一個(gè)合并的函數(shù)來(lái)解決key沖突問(wèn)題: 這里只是簡(jiǎn)單的使用后者覆蓋前者來(lái)解決key重復(fù)問(wèn)題。
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
4. 取出對(duì)象list中的屬性成新的list , 要注意空指向的問(wèn)題
list.stream().map(User::getMessage).collect(Collectors.toList())
5 . 簡(jiǎn)單如重
list.stream().distinct().collect(Collectors.toList());
6 .分組求和
// 通過(guò)userName進(jìn)行分組硬梁,并把用戶的score進(jìn)行求和
Map<String, Integer> invCountMap = list.stream().collect(Collectors.groupingBy(User::getName, Collectors.summingInt(User::getScore)));
// 通過(guò)userName進(jìn)行分組,然后統(tǒng)計(jì)出每個(gè)userName的數(shù)量
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()));