常用方式
代碼如下:
publicMap<Long,String>getIdNameMap(List<Account>accounts){returnaccounts.stream().collect(Collectors.toMap(Account::getId,Account::getUsername));}
收集成實(shí)體本身map
代碼如下:
publicMap<Long,Account>getIdAccountMap(List<Account>accounts){returnaccounts.stream().collect(Collectors.toMap(Account::getId,account->account));}
account -> account是一個(gè)返回本身的lambda表達(dá)式,其實(shí)還可以使用Function接口中的一個(gè)默認(rèn)方法代替,使整個(gè)方法更簡(jiǎn)潔優(yōu)雅:
publicMap<Long,Account>getIdAccountMap(List<Account>accounts){returnaccounts.stream().collect(Collectors.toMap(Account::getId,Function.identity()));}
重復(fù)key的情況
代碼如下:
publicMap<String,Account>getNameAccountMap(List<Account>accounts){returnaccounts.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ù)來解決key沖突問題:
publicMap<String,Account>getNameAccountMap(List<Account>accounts){returnaccounts.stream().collect(Collectors.toMap(Account::getUsername,Function.identity(),(key1,key2)->key2));}
這里只是簡(jiǎn)單的使用后者覆蓋前者來解決key重復(fù)問題。
指定具體收集的map
toMap還有另一個(gè)重載方法,可以指定一個(gè)Map的具體實(shí)現(xiàn)建邓,來收集數(shù)據(jù):
publicMap<String,Account>getNameAccountMap(List<Account>accounts){returnaccounts.stream().collect(Collectors.toMap(Account::getUsername,Function.identity(),(key1,key2)->key2,LinkedHashMap::new));}