Java8 stream处理 Map转 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());

        结果:[UserInfo(userName=123, mobile=a), UserInfo(userName=456, mobile=b), UserInfo(userName=234, mobile=c), UserInfo(userName=789, mobile=z)]

        2、根据Key排序

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

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

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

                   .collect(Collectors.toList());

        结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]

        3、根据Value排序

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

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

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

                  .collect(Collectors.toList());

        结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=c, mobile=234), UserInfo(userName=b, mobile=456), UserInfo(userName=z, mobile=789)]

        3、根据Key排序

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

                  .sorted(Map.Entry.comparingByKey())

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

                  .collect(Collectors.toList());

        结果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]

     4、Map<String,UserInfo> 转 List<String>、List<UserInfo>

      // 取Map中的所有value

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

      // 取Map中所有key

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容