隨筆 - 100  文章 - 50  trackbacks - 0
          <2018年3月>
          25262728123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          常用鏈接

          留言簿(3)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          收藏夾

          我收藏的一些文章!

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          常用方式

          代碼如下:

          public Map<Long, String> getIdNameMap(List<Account> accounts) {     return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername)); } 

          收集成實體本身map

          代碼如下:

          public Map<Long, Account> getIdAccountMap(List<Account> accounts) {     return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account)); } 

          account -> account是一個返回本身的lambda表達式,其實還可以使用Function接口中的一個默認(rèn)方法代替,使整個方法更簡潔優(yōu)雅:

          public Map<Long, Account> getIdAccountMap(List<Account> accounts) {     return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity())); } 

          重復(fù)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是有可能重復(fù)的。toMap有個重載方法,可以傳入一個合并的函數(shù)來解決key沖突問題:

          public Map<String, Account> getNameAccountMap(List<Account> accounts) {     return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2)); } 

          這里只是簡單的使用后者覆蓋前者來解決key重復(fù)問題。

          指定具體收集的map

          toMap還有另一個重載方法,可以指定一個Map的具體實現(xiàn),來收集數(shù)據(jù):

          public Map<String, Account> getNameAccountMap(List<Account> accounts) {     return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new)); } 
           
          轉(zhuǎn)自:https://zacard.net/2016/03/17/java8-list-to-map/
          posted on 2018-03-31 20:21 fly 閱讀(206) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 拜城县| 镇宁| 宁陕县| 蓬安县| 盐山县| 从江县| 西乡县| 儋州市| 绩溪县| 会东县| 通州区| 安图县| 嘉善县| 崇左市| 南华县| 海丰县| 深圳市| 商丘市| 嘉善县| 专栏| 湟源县| 蓬安县| 西藏| 富宁县| 渑池县| 南通市| 漠河县| 临江市| 邻水| 克东县| 禄丰县| 昌邑市| 乌鲁木齐县| 通海县| 娱乐| 丰宁| 石台县| 平安县| 和硕县| 镇巴县| 吐鲁番市|