Stream流的基本使用

List<User> userList = new ArrayList<>();
        userList.add(new User("a", "1", "1", "a"));
        userList.add(new User("b", "2", "2", "b"));
        userList.add(new User("c", "3", "3", "c"));
        userList.add(new User("d", "4", "4", "d"));

        
        //所有值
        userList.forEach(f -> System.out.println(f));
        //name为a的值
        userList.stream().filter(p -> "a".equals(p.getName())).forEach(System.out::println);
        ///name为a 并且为b 的值转为list
        List<User> collect1 = userList.stream().filter(p -> "a".equals(p.getName())).filter(p -> "b".equals(p.getName())).collect(Collectors.toList());
        //name为a 并且为b 的值
        userList.stream().filter(p -> "a".equals(p.getName()) && "b".equals(p.getName())).forEach(a -> System.out.println(a));
        //name为a 或者为b 的name值
        userList.stream().filter(m -> "a".equals(m.getName()) || "b".equals(m.getName())).map(User::getName).forEach(System.out::println);

        //将集合中的name转为set
        Set<String> collectSet = userList.stream().map(User::getName).collect(Collectors.toSet());
        //a c d
        collectSet.forEach(System.out::println);

        //将集合中的name为key,value为同一name的对象集合
        Map<String, List<User>> collect = collectSet.stream().collect(Collectors.toMap(String::new, e -> userList.stream()
                .filter(ele -> ele.getName().equals(e)).collect(Collectors.toList())));
        //a-[a,a]    b-[b]
        collect.forEach((k, v) -> System.out.println(k + "--" + v));

         

        Stream.iterate(10, x->x+2).limit(10).forEach(System.out::println);
        Stream.generate(Math::random).limit(10).forEach(System.out::println);
        Stream.generate(()->new Random().nextInt(10)).limit(10).forEach(System.out::println);


        List<Integer> list = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
        list.stream().filter(i->i % 2==0).distinct().forEach(System.out::println);

        list.stream().limit(3).forEach(System.out::println);
        System.out.println("---------------------------");
        list.stream().skip(3).forEach(System.out::println);

 

posted @ 2022-02-14 09:31  64Byte  阅读(19)  评论(0编辑  收藏  举报