java8中常用list、map转换(Stream、function)

由于经常用到List、Map之间的转换,java8中的新特性function又能很显著的减少代码量,用来取代之前的foreach操作最合适不过了。

以下为代码:

// 将实体类的list,转换为map
List<User> userList = new LinkedList<>();
Map<Integer,User> userMap = userList.
                stream().
                collect(Collectors.toMap(
                item -> item.getId(),// 操作map的key
                item-> item,// 操作map的value
                (v1,v2)->v1
        ));
// 更简单的方式
Map<Integer,User> userMap1 = userList.
                stream().
                collect(Collectors.toMap(
                item -> item.getId(),// 操作map的key
                Function.identity()));// 适用于map的value是item的本身

// List<Integer>  -> List<String>
List<Integer> sourceList = new ArrayList<>();
List<String> targetList = sourceList.stream().
                map(String::valueOf).collect(Collectors.toList());

// List<String>  -> List<Integer>
List<String> sourceList = new ArrayList<>();
List<Integer> targetList = sourceList.stream().
                map((str -> Integer.parseInt(str))).collect(Collectors.toList());

// List<String> 与 String转换
List<String> sourceList = new ArrayList<>();
String targetStr = String.join(",",sourceList );// 第一个参数为形成字符串后的连接符
// String 与 List<String>转换
List<String> targetList = Arrays.asList(targetStr.split(","));// 参数为字符串的连接符
// 注意:以上代码为伪代码,实际操作时应注意非空验证

// 对比串行与并行的效率(stream/parallelStream)
List<Integer> intList = new ArrayList<>();
        for(int i=0;i<100000;i++) {
            intList.add(i);
        }
        
        long t1 = System.currentTimeMillis();
        List<String> collect = intList.stream().map(integer1 -> integer1 + "key").collect(Collectors.toList());
        long t2 = System.currentTimeMillis();
        List<String> collect1 = intList.parallelStream().map(integer1 -> integer1 + "key").collect(Collectors.toList());
        long t3 = System.currentTimeMillis();
        System.out.println("---串行:"+(t2-t1));//---串行:38
        System.out.println("---并行:"+(t3-t2));//---并行:17

于时间:2019/7/26 23:57:30

 

posted @   初见洞洞拐  阅读(681)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示