java8-新特性-04-stream的一些简单应用

1.话不多说直接上代码

import java.util.*;

public class Java8Test2 {


    public static void main(String[] args) {
        List<Integer> collection = 
        Arrays.asList(new Integer[]{14,5,43,89,64,112,55,58,55,61});

        /**
         * Count 计数
         * 计数是一个最终操作,返回Stream中元素的个数,返回值类型是long。
         */
        System.out.println(collection.parallelStream().count());

        /**
         * 求最大值,返回Option,通过Option.get()获取值
         */
        System.out.println(collection.parallelStream().
        max((a,b)->{return a-b;}).get());

        /**
         * 求最小值,返回Option,通过Option.get()获取值
         */
        System.out.println(collection.parallelStream().
        min((a,b)->{return a-b;}).get());

        /**
         * Filter 过滤方法
         */
        Long count =collection.stream().
                filter(num -> num!=null).
                filter(num -> num.intValue()>50).
                count();
        System.out.println("count:"+count);

        System.out.println("1===============");

        /**
         * distinct方法 去除重复
         */
        collection.stream().distinct().forEach(System.out::println);

        System.out.println("2===============");

        /**
         * Sort 排序
         *
         * 需要注意的是,排序只创建了一个排列好后的Stream,而不会影响原有的数据源,
         * 排序之后原数据stringCollection是不会被修改的:
         */
        collection.stream().sorted().forEach(System.out::println);

        /**
         * Map 映射
         * 对于Stream中包含的元素使用给定的转换函数进行转换操作,
         * 新生成的Stream只包含转换生成的元素。
         * 这个方法有三个对于原始类型的变种方法,分别是:mapToInt,mapToLong和mapToDouble。
         * 这三个方法也比较好理解,比如mapToInt就是把原始Stream转换成一个新的Stream,
         * 这个新生成的Stream中的元素都是int类型。
         * 之所以会有这样三个变种方法,可以免除自动装箱/拆箱的额外消耗;
         */
        System.out.println("3=============1");
        collection.stream().mapToLong(Long::valueOf).forEach(System.out::println);
        System.out.println("3=============2");
        Map<Integer, String> map = new HashMap<>();
        for (int i = 0; i < 10; i++) {
            //putIfAbsent 不需要我们做额外的存在性检查
            map.putIfAbsent(i, "val" + i);
        }
        map.forEach((id, val) -> System.out.println(val));
        System.out.println("3=============3");
        // Map 加了很多强大好用的方法
        System.out.println(map.getOrDefault(666, "not found"));  // not found


        /**
         * limit
         * 对一个Stream进行截断操作,获取其前N个元素,
         * 如果原Stream中包含的元素个数小于N,那就获取其所有的元素
         */
        System.out.println("4=============");
        collection.stream().limit(5).forEach(System.out::println);

        /**
         * skip
         * 返回一个丢弃原Stream的前N个元素后剩下元素组成的新Stream,
         * 如果原Stream中包含的元素个数小于N,那么返回空Stream;
         */
        System.out.println("5=============");
        collection.stream().skip(5).forEach(System.out::println);

        /**
         * Match 匹配
         * Stream提供了多种匹配操作,允许检测指定的Predicate是否匹配整个Stream。
         * 所有的匹配操作都是最终操作,并返回一个boolean类型的值。
         */
        System.out.println("6=============");
        boolean anyStartsWithA = collection.stream().anyMatch((s) -> s>100);
        System.out.println(anyStartsWithA);//true  任意一个>100即可

        boolean allStartsWithA = collection.stream().allMatch((s) -> s>100);
        System.out.println(allStartsWithA);//false 全部>100方可

        boolean noneStartsWithZ = collection.stream().noneMatch((s) -> s>500);
        System.out.println(noneStartsWithZ);//true 没有>500的

        /**
         * Reduce 规约
         * 这是一个最终操作,允许通过指定的函数来讲stream中的多个元素规约为一个元素,
         * 规越后的结果是通过Optional接口表示的
         */
        System.out.println("7=============");
        Optional<Integer> reduced = collection.stream().sorted().
        reduce((a,b) -> a + b);
        reduced.ifPresent(System.out::println);

        System.out.println("8=============");
        Random random = new Random();
        random.ints().limit(10).forEach(System.out::println);

        /**
         *统计
         *
         * 另外,一些产生统计结果的收集器也非常有用。它们主要用于
         * int、double、long等基本类型上,
         * 它们可以用来产生类似如下的统计结果。
         */
        System.out.println("9=============");
        IntSummaryStatistics stats = collection.stream().
        mapToInt((x) -> x).summaryStatistics();
        System.out.println("列表中最大的数 : " + stats.getMax());
        System.out.println("列表中最小的数 : " + stats.getMin());
        System.out.println("所有数之和 : " + stats.getSum());
        System.out.println("平均数 : " + stats.getAverage());

    }
}

返回值:

10
112
5
count:7
1===============
14
5
43
89
64
112
55
58
61
2===============
5
14
43
55
55
58
61
64
89
112
3=============1
14
5
43
89
64
112
55
58
55
61
3=============2
val0
val1
val2
val3
val4
val5
val6
val7
val8
val9
3=============3
not found
4=============
14
5
43
89
64
5=============
112
55
58
55
61
6=============
true
false
true
7=============
556
8=============
-553262849
-1377477142
-1193048375
-436306697
-535213014
-1207581915
-1674081021
-705385961
-1102123833
1963385504
9=============
列表中最大的数 : 112
列表中最小的数 : 5
所有数之和 : 556
平均数 : 55.6

2.示例2代码:

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.*;

public class Java8Test2_1 {

    class User{

        private String userName;

        private Integer age;

        public User(){}

        public User(String userName,Integer age){
            this.userName = userName;
            this.age = age;
        }


        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }
    }

    public static void main(String[] args) {
        Java8Test2_1 test = new Java8Test2_1();
        Random random = new Random();
        User[] users = new User[30];
        
        Stream.iterate(0,a->a+1).limit(30).forEach(t->{
            User student = test.new User("user"+random.nextInt(8),t);
            users[t] = student;
        });

        /**
         * 生成List
         */
        List<User> list = Arrays.stream(users).collect(toList());
        list.forEach((x)-> System.out.println("toList : "+x.getUserName() + "-"+x.getAge()));

        System.out.println("111============================");

        /**
         * 生成Set
         */
        Set<User> set = Arrays.stream(users).collect(toSet());
        set.forEach((x)-> System.out.println("toSet : "+x.getUserName() + "-"+x.getAge()));

        System.out.println("222============================");

        /**
         * 如果包含相同的key,则需要提供第三个参数,否则报错
         * 类似于 先分组:然后再求和 value
         */
        Map<String,Integer> map = Arrays.stream(users).collect(toMap(User::getUserName,User::getAge,(s,a)->s+a));
        map.forEach((x,y)-> System.out.println(x+"->"+y));

        System.out.println("333============================");

        /**
         * 生成数组
         */
        User[] s = Arrays.stream(users).toArray(User[]::new);
        for (int i=0;i<s.length;i++)
          System.out.println("Array : " + s[i].getUserName() + "-" + s[i].getAge());

        System.out.println("444============================");

        /**
         * 指定生成的类型
         */
        HashSet<User> hashs = Arrays.stream(users).collect(toCollection(HashSet::new));
        hashs.forEach((x)-> System.out.println("HashSet : "+x.getUserName() + "-"+x.getAge()));

        System.out.println("555============================");

        /**
         * 统计
         */
        IntSummaryStatistics summaryStatistics = Arrays.stream(users).collect(Collectors.summarizingInt(User::getAge));
        System.out.println("getAverage->"+summaryStatistics.getAverage());
        System.out.println("getMax->"+summaryStatistics.getMax());
        System.out.println("getMin->"+summaryStatistics.getMin());
        System.out.println("getCount->"+summaryStatistics.getCount());
        System.out.println("getSum->"+summaryStatistics.getSum());

        System.out.println("666============================");

        /**
         * 分组和分片
         */
        Map<String,List<User>> groupBy = Arrays.stream(users).collect(groupingBy(User::getUserName));
        groupBy.forEach((x,y)-> System.out.println("group : "+x+"->size : "+y.size()));

        System.out.println("777============================");

        /**
         * 如果只有两类,使用partitioningBy会比groupingBy更有效率
         */
        Map<Boolean,List<User>> partitioningBy = Arrays.stream(users).collect(partitioningBy(x->x.getAge()>15));
        partitioningBy.forEach((x,y)-> System.out.println("partitioningBy>groupingBy  : "+x+"-> size:"+y.size()));

        System.out.println("888============================");

        /**
         * downstream指定类型
         */
        Map<String,Set<User>> map_type = Arrays.stream(users).collect(groupingBy(User::getUserName,toSet()));
        map_type.forEach((x,y)-> System.out.println("mapType : "+x+"->size:"+y.size()));

        System.out.println("999============================");

        /**
         * 聚合操作 counting
         */
        Map<String,Long> map1 = Arrays.stream(users).collect(groupingBy(User::getUserName,counting()));
        map1.forEach((x,y)-> System.out.println("聚合操作 counting:"+x+"->"+y));
        /**
         * 聚合操作 summingInt
         */
        Map<String,Integer> map2 = Arrays.stream(users).collect(groupingBy(User::getUserName,summingInt(User::getAge)));
        map2.forEach((x,y)-> System.out.println("聚合操作 summingInt:"+x+"->"+y));
        /**
         * 聚合操作 maxBy
         */
        Map<String,Optional<User>> map3 = Arrays.stream(users).collect(groupingBy(User::getUserName,maxBy(Comparator.comparing(User::getAge))));
        map3.forEach((x,y)-> System.out.println("聚合操作 maxBy:"+x+"->get:"+y.get().getAge()));
        /**
         * 聚合操作 mapping
         */
        Map<String,Set<Integer>> map4 = Arrays.stream(users).collect(groupingBy(User::getUserName,mapping(User::getAge,toSet())));
        map4.forEach((x,y)-> System.out.println("聚合操作 mapping:"+x+"->"+y));

    }
}

输出:

toList : user6-0
toList : user3-1
toList : user3-2
toList : user0-3
toList : user1-4
toList : user4-5
toList : user1-6
toList : user2-7
toList : user7-8
toList : user5-9
toList : user2-10
toList : user1-11
toList : user2-12
toList : user4-13
toList : user5-14
toList : user2-15
toList : user3-16
toList : user2-17
toList : user3-18
toList : user3-19
toList : user3-20
toList : user1-21
toList : user5-22
toList : user7-23
toList : user0-24
toList : user6-25
toList : user1-26
toList : user1-27
toList : user7-28
toList : user7-29
111============================
toSet : user2-7
toSet : user5-22
toSet : user0-3
toSet : user6-0
toSet : user3-18
toSet : user0-24
toSet : user1-6
toSet : user3-2
toSet : user2-15
toSet : user5-9
toSet : user1-11
toSet : user2-12
toSet : user5-14
toSet : user3-1
toSet : user1-4
toSet : user1-26
toSet : user2-10
toSet : user2-17
toSet : user3-19
toSet : user4-13
toSet : user1-21
toSet : user6-25
toSet : user1-27
toSet : user3-16
toSet : user7-8
toSet : user7-29
toSet : user4-5
toSet : user3-20
toSet : user7-28
toSet : user7-23
222============================
user1->95
user2->61
user0->27
user7->88
user5->45
user6->25
user3->76
user4->18
333============================
Array : user6-0
Array : user3-1
Array : user3-2
Array : user0-3
Array : user1-4
Array : user4-5
Array : user1-6
Array : user2-7
Array : user7-8
Array : user5-9
Array : user2-10
Array : user1-11
Array : user2-12
Array : user4-13
Array : user5-14
Array : user2-15
Array : user3-16
Array : user2-17
Array : user3-18
Array : user3-19
Array : user3-20
Array : user1-21
Array : user5-22
Array : user7-23
Array : user0-24
Array : user6-25
Array : user1-26
Array : user1-27
Array : user7-28
Array : user7-29
444============================
HashSet : user2-7
HashSet : user5-22
HashSet : user0-3
HashSet : user6-0
HashSet : user3-18
HashSet : user0-24
HashSet : user1-6
HashSet : user3-2
HashSet : user2-15
HashSet : user5-9
HashSet : user1-11
HashSet : user2-12
HashSet : user5-14
HashSet : user3-1
HashSet : user1-4
HashSet : user1-26
HashSet : user2-10
HashSet : user2-17
HashSet : user3-19
HashSet : user4-13
HashSet : user1-21
HashSet : user6-25
HashSet : user1-27
HashSet : user3-16
HashSet : user7-8
HashSet : user7-29
HashSet : user4-5
HashSet : user3-20
HashSet : user7-28
HashSet : user7-23
555============================
getAverage->14.5
getMax->29
getMin->0
getCount->30
getSum->435
666============================
group : user1->size : 6
group : user2->size : 5
group : user0->size : 2
group : user7->size : 4
group : user5->size : 3
group : user6->size : 2
group : user3->size : 6
group : user4->size : 2
777============================
partitioningBy>groupingBy  : false-> size:16
partitioningBy>groupingBy  : true-> size:14
888============================
mapType : user1->size:6
mapType : user2->size:5
mapType : user0->size:2
mapType : user7->size:4
mapType : user5->size:3
mapType : user6->size:2
mapType : user3->size:6
mapType : user4->size:2
999============================
聚合操作 counting:user1->6
聚合操作 counting:user2->5
聚合操作 counting:user0->2
聚合操作 counting:user7->4
聚合操作 counting:user5->3
聚合操作 counting:user6->2
聚合操作 counting:user3->6
聚合操作 counting:user4->2
聚合操作 summingInt:user1->95
聚合操作 summingInt:user2->61
聚合操作 summingInt:user0->27
聚合操作 summingInt:user7->88
聚合操作 summingInt:user5->45
聚合操作 summingInt:user6->25
聚合操作 summingInt:user3->76
聚合操作 summingInt:user4->18
聚合操作 maxBy:user1->get:27
聚合操作 maxBy:user2->get:17
聚合操作 maxBy:user0->get:24
聚合操作 maxBy:user7->get:29
聚合操作 maxBy:user5->get:22
聚合操作 maxBy:user6->get:25
聚合操作 maxBy:user3->get:20
聚合操作 maxBy:user4->get:13
聚合操作 mapping:user1->[4, 21, 6, 26, 11, 27]
聚合操作 mapping:user2->[17, 7, 10, 12, 15]
聚合操作 mapping:user0->[3, 24]
聚合操作 mapping:user7->[23, 8, 28, 29]
聚合操作 mapping:user5->[22, 9, 14]
聚合操作 mapping:user6->[0, 25]
聚合操作 mapping:user3->[16, 1, 2, 18, 19, 20]
聚合操作 mapping:user4->[5, 13]

感谢:https://blog.csdn.net/cdw8131197/article/details/68553148

猜你喜欢

转载自blog.csdn.net/ming1215919/article/details/82803488