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

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));
    }
}

 

 

posted @ 2022-11-11 14:55  wode林夕  阅读(34)  评论(0编辑  收藏  举报  来源