Java8 stream處理 Map轉(zhuǎn) List

Map<String,String> map1 = new HashMap<>();

? ? ? ? map1.put("a","123");

? ? ? ? map1.put("b","456");

? ? ? ? map1.put("z","789");

? ? ? ? map1.put("c","234");

? ? ? ? 1、默認順序

? ? ? ? List<UserInfo> list0 = map1.entrySet().stream()

                   .map(e -> new UserInfo(e.getValue(), e.getKey()))

                   .collect(Collectors.toList());

? ? ? ? 結(jié)果:[UserInfo(userName=123, mobile=a), UserInfo(userName=456, mobile=b), UserInfo(userName=234, mobile=c), UserInfo(userName=789, mobile=z)]

? ? ? ? 2、根據(jù)Key排序

? ? ? ? List<UserInfo> list1 = map1.entrySet().stream()

                   .sorted(Comparator.comparing(e -> e.getKey()))

.map(e -> new UserInfo(e.getKey(), e.getValue()))

                   .collect(Collectors.toList());

? ? ? ? 結(jié)果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]

? ? ? ? 3、根據(jù)Value排序

? ? ? ? List<UserInfo> list2 = map1.entrySet().stream()

                  .sorted(Comparator.comparing(Map.Entry::getValue))

                  .map(e -> new UserInfo(e.getKey(), e.getValue()))

                  .collect(Collectors.toList());

? ? ? ? 結(jié)果:[UserInfo(userName=a, mobile=123), UserInfo(userName=c, mobile=234), UserInfo(userName=b, mobile=456), UserInfo(userName=z, mobile=789)]

? ? ? ? 3、根據(jù)Key排序

? ? ? ? List<UserInfo> list3 = map1.entrySet().stream()

                  .sorted(Map.Entry.comparingByKey())

                  .map(e -> new UserInfo(e.getKey(), e.getValue()))

                  .collect(Collectors.toList());

? ? ? ? 結(jié)果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]

     4、Map<String,UserInfo> 轉(zhuǎn) List<String>、List<UserInfo>

      // 取Map中的所有value

      結(jié)果:List<UserInfo> userInfoList = retMap.values().stream().collect(Collectors.toList());

      // 取Map中所有key

      結(jié)果:List<String> strList = retMap.keySet().stream().collect(Collectors.toList());

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容