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

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值