List 集合通过创建stream 流的方式转成map集合

本文介绍了如何使用Java 8的Stream API对用户实体List进行去重操作,并演示了两种不同的toMap方法实现,包括单线程串行流和多线程并行流。
public class test7 {
    public static void main(String[] args) {
        ArrayList<UserEntity> list = new ArrayList<>();
        list.add(new UserEntity("xialijun",12));
        list.add(new UserEntity("xia",24));
        list.add(new UserEntity("qwer",1234));
        list.add(new UserEntity("qwet",1223));
        list.add(new UserEntity("qwey",1235));
        list.add(new UserEntity("qweye",1235));
        //流: stream  串行流  单线程
        //    parallelStream()  并行流  多线程  效率高
        //
        Set<UserEntity> collect = list.stream().collect(Collectors.toSet());
        collect.forEach(x->{
            System.out.println(x.toString());
        });
        System.out.println("========================================");
        collect.forEach(System.out::println);
        Set<UserEntity> collect1 = list.parallelStream().collect(Collectors.toSet());
        //key     
        //UserEntity   list  集合中的数据
      第一种写法 :
//        Map<String, UserEntity> map = list.stream().collect(Collectors.toMap(new Function<UserEntity, String>() {
//            @Override
//            public String apply(UserEntity userEntity) {
//                return userEntity.getName();
//            }
//            //value
//        }, new Function<UserEntity, UserEntity>() {
//            @Override
//            public UserEntity apply(UserEntity userEntity) {
//                return userEntity;
//            }
//        }));
//        map.forEach(new BiConsumer<String, UserEntity>() {
//            @Override
//            public void accept(String s, UserEntity userEntity) {
//                System.out.println(s + "====" + userEntity);
//            }
//        });
       第二种写法
        Map<String, UserEntity> map = list.stream()
                //key----->UserEntity::getName,
                //value----->    userEntity -> userEntity
                .collect(Collectors.toMap(UserEntity::getName,
                        userEntity -> userEntity));
        map.forEach((s, userEntity) -> System.out.println(s + "====" + userEntity));
    }
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大大怪~将军

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值