<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    隨筆 - 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接口中的一個默認方法代替,使整個方法更簡潔優雅:

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

    重復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沖突問題:

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

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

    指定具體收集的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)); } 
     
    轉自:https://zacard.net/2016/03/17/java8-list-to-map/
    posted on 2018-03-31 20:21 fly 閱讀(200) 評論(0)  編輯  收藏

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


    網站導航:
     
    主站蜘蛛池模板: 亚洲麻豆精品国偷自产在线91| 国产精品无码免费播放| 亚洲av麻豆aⅴ无码电影| 亚洲国产无线乱码在线观看| 在线精品免费视频无码的| 亚洲色偷偷色噜噜狠狠99网| 麻豆国产VA免费精品高清在线 | 国产精品美女自在线观看免费| 日韩亚洲产在线观看| 免费高清小黄站在线观看| 亚洲码和欧洲码一码二码三码| 免费一级毛片不卡不收费| 日韩一级片免费观看| 精品国产亚洲一区二区三区| 久久九九全国免费| 亚洲网红精品大秀在线观看| 国产精品成人免费视频网站京东 | 免费又黄又爽又猛大片午夜 | 久久人午夜亚洲精品无码区| 免费吃奶摸下激烈视频| a毛片成人免费全部播放| 久久久久久久久亚洲| 无限动漫网在线观看免费 | 国产精品1024在线永久免费| 国产AV无码专区亚洲A∨毛片| 99久久免费精品视频| 亚洲 日韩经典 中文字幕| 四虎永久免费网站免费观看| 97超高清在线观看免费视频| 亚洲成a人片在线网站| 国产高清免费在线| 久久er国产精品免费观看2| 亚洲国产精品午夜电影| 国产成人免费高清在线观看| a级毛片免费全部播放| 亚洲 欧洲 日韩 综合在线| 亚洲熟女少妇一区二区| 免费无码又黄又爽又刺激| 久青草视频在线观看免费| 99热亚洲色精品国产88| 丁香五月亚洲综合深深爱|