<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 閱讀(201) 評論(0)  編輯  收藏

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


    網站導航:
     
    主站蜘蛛池模板: 97在线视频免费播放| 99视频全部免费精品全部四虎| 18禁止观看免费私人影院| 亚洲精选在线观看| 国产精成人品日日拍夜夜免费| 国产四虎免费精品视频| 亚洲伊人tv综合网色| 久久免费观看国产精品88av| 亚洲国产精品成人精品无码区 | 最近免费中文字幕中文高清 | 亚洲精品无码国产| 亚洲精品av无码喷奶水糖心| 9久久免费国产精品特黄| 中文字幕日韩亚洲| 国产高清不卡免费视频| 中文字幕亚洲精品| 大学生高清一级毛片免费| 国产精品亚洲а∨无码播放不卡| 99re免费在线视频| 亚洲M码 欧洲S码SSS222| 一级毛片在播放免费| 亚洲色欲久久久综合网| 中文字幕天天躁日日躁狠狠躁免费| 亚洲精品乱码久久久久久下载 | 亚洲乱码日产精品一二三| 免费的全黄一级录像带| 亚洲性色高清完整版在线观看| 成全视频在线观看免费高清动漫视频下载| 亚洲精品无码久久久久A片苍井空| 亚洲国产精品激情在线观看 | 亚洲一级毛片免费观看| 日日麻批免费40分钟无码| 一本色道久久88—综合亚洲精品 | 成人免费无码大片a毛片软件| 污网站在线观看免费| 久久精品国产亚洲| 免费观看男人免费桶女人视频| 亚洲国产综合在线| 男人的天堂亚洲一区二区三区| 亚洲手机中文字幕| 亚洲成AV人在线观看网址|