Stream流②——Stream常用操作

224 阅读19分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第8天,点击查看活动详情

1. Stream常用操作(⭐)

1.1 创建流

单列集合

单列集合: 集合对象.stream()

        List<Author> authors = getAuthors();
        Stream<Author> stream = authors.stream();

数组

数组:Arrays.stream(数组)或者使用Stream.of来创建

        Integer[] arr = {1,2,3,4,5};
        Stream<Integer> stream = Arrays.stream(arr);
        Stream<Integer> stream2 = Stream.of(arr);

双列集合

双列集合:转换成单列集合后再创建

        Map<String,Integer> map = new HashMap<>();
        map.put("蜡笔小新",19);
        map.put("黑子",17);
        map.put("日向翔阳",16);
​
        Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();

1.2 中间操作

filter

可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。

img

例如:

打印所有姓名长度大于1的作家的姓名

        List<Author> authors = getAuthors();
        authors.stream()
                .filter(author -> author.getName().length()>1)
                .forEach(author -> System.out.println(author.getName()));

map

可以把对流中的元素进行计算或转换。(可以把一个类转成另一个类)

image-20220724210552569

    @Test
    void mapTest(){
        String[] strArr = { "abcd", "bcdd", "defde", "fTr" };
        List<String> strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());
​
        List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);
        List<Integer> intListNew = intList.stream().map(x -> x + 3).collect(Collectors.toList());
​
        System.out.println("每个元素大写:" + strList);
        System.out.println("每个元素+3:" + intListNew);
    }
每个元素大写:[ABCD, BCDD, DEFDE, FTR]
每个元素+3[4, 6, 8, 10, 12, 14]

例如:

打印所有作家的姓名

        List<Author> authors = getAuthors();
​
        authors.stream()
                .map(author -> author.getName())
                .forEach(name->System.out.println(name));
​
​
//        打印所有作家的姓名
        List<Author> authors = getAuthors();
​
//        authors.stream()
//                .map(author -> author.getName())
//                .forEach(s -> System.out.println(s));
​
        authors.stream()
                .map(author -> author.getAge())
                .map(age->age+10)
                .forEach(age-> System.out.println(age));

flatMap

map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。

img

例一:

打印所有书籍的名字。要求对重复的元素进行去重。

//        打印所有书籍的名字。要求对重复的元素进行去重。
        List<Author> authors = getAuthors();
​
        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .forEach(book -> System.out.println(book.getName()));

例二:

打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情

//        打印现有数据的所有分类。要求对分类进行去重。不能出现这种格式:哲学,爱情     爱情
        List<Author> authors = getAuthors();
        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
                .distinct()
                .forEach(category-> System.out.println(category));

sorted

可以对流中的元素进行排序。

有两种排序:

  • sorted():自然排序,流中元素需实现Comparable接口
  • sorted(Comparator com):Comparator排序器自定义排序

例如:

对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。

//        对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素。
    @Test
    void test10(){
        List<Author> authors = getAuthors();
        // 正常执行
        authors.stream()
                .distinct()
                .sorted((o1, o2) -> o2.getAge()-o1.getAge())
                .forEach(author -> System.out.println(author.getAge()));

        // 没有实现Comparable方法,报错
        authors.stream()
                .distinct()
                .sorted()
                .forEach(author -> System.out.println(author.getAge()));
    }

注意:如果调用空参的sorted()方法,需要流中的元素是实现了Comparable。

33
15
14

java.lang.ClassCastException: class com.example.stream_learn717.pojo.Author cannot be cast to class java.lang.Comparable (com.example.stream_learn717.pojo.Author is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')

	at java.base/java.util.Comparators$NaturalOrderComparator.compare(Comparators.java:47)
	at java.base/java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
	at java.base/java.util.TimSort.sort(TimSort.java:220)

案例:将员工按工资由高到低(工资一样则按年龄由大到小)排序

    @Test
    void test9(){
        List<Person> personList = new ArrayList<Person>();
​
        personList.add(new Person("Sherry", 9000, 24, "female", "New York"));
        personList.add(new Person("Tom", 8900, 22, "male", "Washington"));
        personList.add(new Person("Jack", 9000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 8800, 26, "male", "New York"));
        personList.add(new Person("Alisa", 9000, 26, "female", "New York"));
​
        // 按工资升序排序(自然排序)
        List<String> newList = personList.stream()
                .sorted(Comparator.comparing(Person::getSalary))
                .map(Person::getName)
                .collect(Collectors.toList());
        
        // 按工资倒序排序
        List<String> newList2 = personList.stream()
                .sorted(Comparator.comparing(Person::getSalary).reversed())
                .map(Person::getName)
                .collect(Collectors.toList());
        
        // 先按工资再按年龄升序排序
        List<String> newList3 = personList.stream()
                .sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge))
                .map(Person::getName)
                .collect(Collectors.toList());
        
        // 先按工资再按年龄自定义排序(降序)
        List<String> newList4 = personList.stream().sorted((p1, p2) -> {
            if (p1.getSalary() == p2.getSalary()) {
                return p2.getAge() - p1.getAge();
            } else {
                return p2.getSalary() - p1.getSalary();
            }
        }).map(Person::getName).collect(Collectors.toList());
​
        System.out.println("按工资升序排序:" + newList);
        System.out.println("按工资降序排序:" + newList2);
        System.out.println("先按工资再按年龄升序排序:" + newList3);
        System.out.println("先按工资再按年龄自定义降序排序:" + newList4);
​
    }

运行结果

按工资升序排序:[Lily, Tom, Sherry, Jack, Alisa]
按工资降序排序:[Sherry, Jack, Alisa, Tom, Lily]
先按工资再按年龄升序排序:[Lily, Tom, Sherry, Jack, Alisa]
先按工资再按年龄自定义降序排序:[Alisa, Jack, Sherry, Tom, Lily]

distinct

可以去除流中的重复元素。

img

例如:

打印所有作家的姓名,并且要求其中不能有重复元素。

        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .forEach(author -> System.out.println(author.getName()));

注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重写equals方法。

limit

可以设置流的最大长度,超出的部分将被抛弃。

img

例如:

对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印其中年龄最大的两个作家的姓名。

        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .sorted()
                .limit(2)
                .forEach(author -> System.out.println(author.getName()));

skip

跳过流中的前n个元素,返回剩下的元素

img

例如:

打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。

//        打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .sorted()
                .skip(1)
                .forEach(author -> System.out.println(author.getName()));

peek

peekforeach,都可以用于对元素进行遍历然后逐个的进行处理。

区别:

  • peek属于中间方法,而foreach属于终止方法
  • 意味着peek只能作为管道中途的一个处理步骤,而没法直接执行得到结果,其后面必须还要有其它终止操作的时候才会被执行;
  • 而foreach作为无返回值的终止方法,则可以直接执行相关操作。
    @Test
    void test12(){
        List<Author> authors = getAuthors();

        // 演示点1: 仅peek操作,最终不会执行
        System.out.println("----before peek----");
        authors.stream()
            .peek(author -> System.out.println(author));
        System.out.println("----after peek----" + "\n");

        // 演示点2: 仅foreach操作,最终会执行
        System.out.println("----before foreach----");
        authors.stream()
            .forEach(author -> System.out.println(author));
        System.out.println("----after foreach----" + "\n");

        // 演示点3: peek操作后面增加终止操作,peek会执行
        System.out.println("----before peek and collect----");
        List<Author> collect = authors.stream()
            .peek(author -> System.out.println(author.getBooks()))
            .collect(Collectors.toList());
        System.out.println("----after peek and collect----" + "\n");
    }

运行结果

输出结果可以看出,peek独自调用时并没有被执行、但peek后面加上终止操作之后便可以被执行,而foreach可以直接被执行:

----before peek----
----after peek----
​
----before foreach----
Author(id=1, name=蒙多, age=33, intro=一个从菜刀中明悟哲理的祖安人, books=[Book(id=1, name=刀的两侧是光明与黑暗, category=哲学,爱情, score=88, intro=用一把刀划分了爱恨), Book(id=2, name=一个人不能死在同一把刀下, category=个人成长,爱情, score=99, intro=讲述如何从失败中明悟真理)])
Author(id=2, name=亚拉索, age=15, intro=狂风也追逐不上他的思考速度, books=[Book(id=3, name=那风吹不到的地方, category=哲学, score=85, intro=带你用思维去领略世界的尽头), Book(id=3, name=那风吹不到的地方, category=哲学, score=85, intro=带你用思维去领略世界的尽头), Book(id=4, name=吹或不吹, category=爱情,个人传记, score=56, intro=一个哲学家的恋爱观注定很难把他所在的时代理解)])
Author(id=3, name=易, age=14, intro=是这个世界在限制他的思维, books=[Book(id=5, name=你的剑就是我的剑, category=爱情, score=56, intro=无法想象一个武者能对他的伴侣这么的宽容), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?)])
Author(id=3, name=易, age=14, intro=是这个世界在限制他的思维, books=[Book(id=5, name=你的剑就是我的剑, category=爱情, score=56, intro=无法想象一个武者能对他的伴侣这么的宽容), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?)])
----after foreach----
​
----before peek and collect----
[Book(id=1, name=刀的两侧是光明与黑暗, category=哲学,爱情, score=88, intro=用一把刀划分了爱恨), Book(id=2, name=一个人不能死在同一把刀下, category=个人成长,爱情, score=99, intro=讲述如何从失败中明悟真理)]
[Book(id=3, name=那风吹不到的地方, category=哲学, score=85, intro=带你用思维去领略世界的尽头), Book(id=3, name=那风吹不到的地方, category=哲学, score=85, intro=带你用思维去领略世界的尽头), Book(id=4, name=吹或不吹, category=爱情,个人传记, score=56, intro=一个哲学家的恋爱观注定很难把他所在的时代理解)]
[Book(id=5, name=你的剑就是我的剑, category=爱情, score=56, intro=无法想象一个武者能对他的伴侣这么的宽容), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?)]
[Book(id=5, name=你的剑就是我的剑, category=爱情, score=56, intro=无法想象一个武者能对他的伴侣这么的宽容), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?), Book(id=6, name=风与剑, category=个人传记, score=100, intro=两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?)]
----after peek and collect----

1.3 终结操作

forEach

对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。Stream也是支持类似集合的遍历和匹配元素的,只是Stream中的元素是以Optional类型存在的。 Stream的遍历、匹配非常简单。

例子:

输出所有作家的名字

//        输出所有作家的名字
        List<Author> authors = getAuthors();
​
        authors.stream()
                .map(author -> author.getName())
                .distinct()
                .forEach(name-> System.out.println(name));
​

count

可以用来获取当前流中元素的个数。

    @Test
    void countTest(){
        List<Integer> list = Arrays.asList(7, 6, 4, 8, 2, 11, 9);
        long count = list.stream().filter(x -> x > 6).count();
        System.out.println("list中大于6的元素个数:" + count);
    }
list中大于6的元素个数:4

例子:

打印这些作家的所出书籍的数目,注意删除重复元素。

//        打印这些作家的所出书籍的数目,注意删除重复元素。
        List<Author> authors = getAuthors();
​
        long count = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .count();
        System.out.println(count);

max&min

可以用来或者流中的最值。

例子:

分别获取这些作家的所出书籍的最高分和最低分并打印。

//        分别获取这些作家的所出书籍的最高分和最低分并打印。
        //Stream<Author>  -> Stream<Book> ->Stream<Integer>  ->求值

        List<Author> authors = getAuthors();
        Optional<Integer> max = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .max((score1, score2) -> score1 - score2);

        Optional<Integer> min = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .min((score1, score2) -> score1 - score2);
        System.out.println(max.get());
        System.out.println(min.get());
    @Test
    void maxTest(){
        List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
        Optional<String> max = list.stream().max(Comparator.comparing(String::length));
        System.out.println("最长的字符串:" + max.get());
    }
最长的字符串:weoujgsd
    @Test
    void maxTest(){
        List<Integer> list = Arrays.asList(7, 6, 9, 4, 11, 6);
​
        // 自然排序
        Optional<Integer> max = list.stream().max(Integer::compareTo);
        // 自定义排序
        Optional<Integer> max2 = list.stream().max((o1, o2) -> o1.compareTo(o2));
        System.out.println("自然排序的最大值:" + max.get());
        System.out.println("自定义排序的最大值:" + max2.get());
    }
自然排序的最大值:11
自定义排序的最大值:11
    @Test
    void maxTest(){
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
        personList.add(new Person("Anni", 8200, 24, "female", "New York"));
        personList.add(new Person("Owen", 9500, 25, "male", "New York"));
        personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
​
        Optional<Person> max = personList.stream().max(Comparator.comparingInt(Person::getSalary));
        System.out.println("员工工资最大值:" + max.get().getSalary());
    }
员工工资最大值:9500

collect

原理:讲透JAVA Stream的collect用法与原理,远比你想象的更强大

因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。toListtoSettoMap比较常用,另外还有toCollectiontoConcurrentMap等复杂一些的用法。

  • 简单点说,就是把当前流转换成一个集合。
  • collect主要依赖java.util.stream.Collectors类内置的静态方法。

例子:

获取一个存放所有作者名字的List集合。

//        获取一个存放所有作者名字的List集合。
        List<Author> authors = getAuthors();
        List<String> nameList = authors.stream()
                .map(author -> author.getName())
                .collect(Collectors.toList());
        System.out.println(nameList);

获取一个所有书名的Set集合。

//        获取一个所有书名的Set集合。
        List<Author> authors = getAuthors();
        Set<Book> books = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .collect(Collectors.toSet());
​
        System.out.println(books);

获取一个Map集合,map的key为作者名,value为List

//        获取一个Map集合,map的key为作者名,value为List<Book>
        List<Author> authors = getAuthors();
​
        Map<String, List<Book>> map = authors.stream()
                .distinct()
                .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
​
        System.out.println(map);

归集(toList/toSet/toMap)

因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。toListtoSettoMap比较常用,另外还有toCollectiontoConcurrentMap等复杂一些的用法。

下面用一个案例演示toListtoSettoMap

    @Test
    void test3(){
        // 针对数组的操作
        List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);
        List<Integer> listNew = list.stream()
                .filter(x -> x % 2 == 0)
                .collect(Collectors.toList());
        Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
        // 针对对象集合的操作
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
        personList.add(new Person("Anni", 8200, 24, "female", "New York"));

        Map<?, Person> map = personList.stream()
                .filter(p -> p.getSalary() > 8000)
                .collect(Collectors.toMap(Person::getName, p -> p));
        System.out.println("toList:" + listNew);
        System.out.println("toSet:" + set);
        System.out.println("toMap:" + map);
    }

运行结果

toList:[6, 4, 6, 6, 20]
toSet:[4, 20, 6]
toMap:{Tom=Person(name=Tom, salary=8900, age=23, sex=male, area=New York), Anni=Person(name=Anni, salary=8200, age=24, sex=female, area=New York)}

统计(count/averaging)

Collectors提供了一系列用于数据统计的静态方法:

  • 计数:count
  • 平均值:averagingIntaveragingLongaveragingDouble
  • 最值:maxByminBy
  • 求和:summingIntsummingLongsummingDouble
  • 统计以上所有:summarizingIntsummarizingLongsummarizingDouble
    @Test
    void test5(){
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 21, "female", "Washington"));

        // 求总数
        Long count = personList.stream().collect(Collectors.counting());
        // 求平均工资
        Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
        // 求最高工资
        Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
        // 求工资之和
        Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
        // 一次性统计所有信息
        DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));

        System.out.println("员工总数:" + count);
        System.out.println("员工平均工资:" + average);
        System.out.println("员工工资总和:" + sum);
        System.out.println("员工工资所有统计:" + collect);
    }

运行结果

员工总数:3
员工平均工资:7900.0
员工工资总和:23700
员工工资所有统计:DoubleSummaryStatistics{count=3, sum=23700.000000, min=7000.000000, average=7900.000000, max=8900.000000}

分组(partitioningBy/groupingBy)

  • 分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
  • 分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。

img

	 @Test
    void test6(){
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, "male", "New York"));
        personList.add(new Person("Jack", 7000, "male", "Washington"));
        personList.add(new Person("Lily", 7800, "female", "Washington"));
        personList.add(new Person("Anni", 8200, "female", "New York"));
        personList.add(new Person("Owen", 9500, "male", "New York"));
        personList.add(new Person("Alisa", 7900, "female", "New York"));

        // 将员工按薪资是否高于8000分组
        Map<Boolean, List<Person>> part = personList.stream()
                .collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
        
        // 将员工按性别分组
        Map<String, List<Person>> group = personList.stream()
                .collect(Collectors.groupingBy(Person::getSex));

        // 将员工先按性别分组,再按地区分组
        Map<String, Map<String, List<Person>>> group2 = personList.stream()
                .collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));

        System.out.println("员工按薪资是否大于8000分组情况:" + part);
        System.out.println("员工按性别分组情况:" + group);
        System.out.println("员工按性别、地区:" + group2);
    }

运行结果

员工按薪资是否大于8000分组情况:{false=[Person(name=Jack, salary=7000, age=0, sex=male, area=Washington), Person(name=Lily, salary=7800, age=0, sex=female, area=Washington), Person(name=Alisa, salary=7900, age=0, sex=female, area=New York)], true=[Person(name=Tom, salary=8900, age=0, sex=male, area=New York), Person(name=Anni, salary=8200, age=0, sex=female, area=New York), Person(name=Owen, salary=9500, age=0, sex=male, area=New York)]}
员工按性别分组情况:{female=[Person(name=Lily, salary=7800, age=0, sex=female, area=Washington), Person(name=Anni, salary=8200, age=0, sex=female, area=New York), Person(name=Alisa, salary=7900, age=0, sex=female, area=New York)], male=[Person(name=Tom, salary=8900, age=0, sex=male, area=New York), Person(name=Jack, salary=7000, age=0, sex=male, area=Washington), Person(name=Owen, salary=9500, age=0, sex=male, area=New York)]}
员工按性别、地区:{female={New York=[Person(name=Anni, salary=8200, age=0, sex=female, area=New York), Person(name=Alisa, salary=7900, age=0, sex=female, area=New York)], Washington=[Person(name=Lily, salary=7800, age=0, sex=female, area=Washington)]}, male={New York=[Person(name=Tom, salary=8900, age=0, sex=male, area=New York), Person(name=Owen, salary=9500, age=0, sex=male, area=New York)], Washington=[Person(name=Jack, salary=7000, age=0, sex=male, area=Washington)]}}

接合(joining)

joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。

    @Test
    void test7(){
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 21, "female", "Washington"));

        String names = personList.stream()
                .map(p -> p.getName())
                .collect(Collectors.joining(","));
        System.out.println("所有员工的姓名:" + names);
        
        List<String> list = Arrays.asList("A", "B", "C");
        String string = list.stream()
                .collect(Collectors.joining("-"));
        System.out.println("拼接后的字符串:" + string);
    }

运行结果

所有员工的姓名:Tom,Jack,Lily
拼接后的字符串:A-B-C

归约(reducing)

Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。

    @Test
    void test8(){
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 21, "female", "Washington"));

        // 每个员工减去起征点后的薪资之和
        Integer sum = personList.stream()
                // 使用的时候Collectors类提供的reducing方法
                .collect(Collectors.reducing(0, Person::getSalary, (i, j) -> (i + j - 5000)));
        System.out.println("员工扣税薪资总和:" + sum);

        // stream的reduce
        Optional<Integer> sum2 = personList.stream()
                .map(Person::getSalary)
                .reduce(Integer::sum);
        System.out.println("员工薪资总和:" + sum2.get());
    }

运行结果

员工扣税薪资总和:8700
员工薪资总和:23700

查找与匹配

Stream也是支持类似集合的遍历和匹配元素的,只是Stream中的元素是以Optional类型存在的。Stream的遍历、匹配非常简单。

img

anyMatch

可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。

例子:

判断是否有年龄在29以上的作家

//        判断是否有年龄在29以上的作家
        List<Author> authors = getAuthors();
        boolean flag = authors.stream()
                .anyMatch(author -> author.getAge() > 29);
        System.out.println(flag);

allMatch

可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。

例子:

判断是否所有的作家都是成年人

//        判断是否所有的作家都是成年人
        List<Author> authors = getAuthors();
        boolean flag = authors.stream()
                .allMatch(author -> author.getAge() >= 18);
        System.out.println(flag);

noneMatch

可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false

例子:

判断作家是否都没有超过100岁的。

//        判断作家是否都没有超过100岁的。
        List<Author> authors = getAuthors();

        boolean b = authors.stream()
                .noneMatch(author -> author.getAge() > 100);

        System.out.println(b);

findAny

获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。

例子:

获取任意一个年龄大于18的作家,如果存在就输出他的名字

//        获取任意一个年龄大于18的作家,如果存在就输出他的名字
        List<Author> authors = getAuthors();
        Optional<Author> optionalAuthor = authors.stream()
                .filter(author -> author.getAge()>18)
                .findAny();

        optionalAuthor.ifPresent(author -> System.out.println(author.getName()));

findFirst

获取流中的第一个元素。

例子:

获取一个年龄最小的作家,并输出他的姓名。

//        获取一个年龄最小的作家,并输出他的姓名。
        List<Author> authors = getAuthors();
        Optional<Author> first = authors.stream()
                .sorted((o1, o2) -> o1.getAge() - o2.getAge())
                .findFirst();
​
        first.ifPresent(author -> System.out.println(author.getName()));

reduce归并

img

对流中的数据按照你指定的计算方式计算出一个结果。(缩减操作)

reduce的作用是把stream中的元素给组合起来,我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。

(源码)reduce两个参数的重载形式内部的计算方式如下:

T result = identity;
for (T element : this stream)
    result = accumulator.apply(result, element)
return result;

其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。

案例一:求Integer集合的元素之和、乘积和最大值。

    @Test
    void reduceTest(){
        List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
        // 求和方式1
        Optional<Integer> sum = list.stream().reduce((x, y) -> x + y);
        // 求和方式2
        Optional<Integer> sum2 = list.stream().reduce(Integer::sum);
        // 求和方式3
        Integer sum3 = list.stream().reduce(0, Integer::sum);
        // 求乘积
        Optional<Integer> product = list.stream().reduce( (x, y) -> x * y);
        Integer reduce = list.stream().reduce(0, (x, y) -> x * y);
        // 求最大值方式1
        Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y);
        // 求最大值写法2
        Integer max2 = list.stream().reduce(1, (a, b) -> Integer.max(a, b));
​
        System.out.println("list求和:" + sum.get() + "," + sum2.get() + "," + sum3);
        System.out.println("list求积:" + product.get());
        System.out.println("list求积:" + reduce);
        System.out.println("list求和:" + max.get() + "," + max2);
​
    }
list求和:29,29,29
list求积:2112
list求积:0
list求和:11,11

例子:

使用reduce求所有作者年龄的和

//        使用reduce求所有作者年龄的和
        List<Author> authors = getAuthors();
        Integer sum = authors.stream()
                .distinct()
                .map(author -> author.getAge())
                .reduce(0, (result, element) -> result + element);
        System.out.println(sum);

使用reduce求所有作者中年龄的最大值

//        使用reduce求所有作者中年龄的最大值
        List<Author> authors = getAuthors();
        Integer max = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MIN_VALUE, (result, element) -> result < element ? element : result);
​
        System.out.println(max);

使用reduce求所有作者中年龄的最小值

//        使用reduce求所有作者中年龄的最小值
        List<Author> authors = getAuthors();
        Integer min = authors.stream()
                .map(author -> author.getAge())
                .reduce(Integer.MAX_VALUE, (result, element) -> result > element ? element : result);
        System.out.println(min);

reduce一个参数的重载形式内部的计算

 	 boolean foundAny = false;
     T result = null;
     for (T element : this stream) {
         if (!foundAny) {
             foundAny = true;
             result = element;
         }
         else
             result = accumulator.apply(result, element);
     }
     return foundAny ? Optional.of(result) : Optional.empty();

如果用一个参数的重载方法去求最小值代码如下:

        //        使用reduce求所有作者中年龄的最小值
        List<Author> authors = getAuthors();
        Optional<Integer> minOptional = authors.stream()
                .map(author -> author.getAge())
                .reduce((result, element) -> result > element ? element : result);
        minOptional.ifPresent(age-> System.out.println(age));

案例二:求所有员工的工资之和和最高工资。

    @Test
    void reduceTest(){
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
        personList.add(new Person("Anni", 8200, 24, "female", "New York"));
        personList.add(new Person("Owen", 9500, 25, "male", "New York"));
        personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
​
        // 求工资之和方式1:
        Optional<Integer> sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum);
        // 求工资之和方式2:
        Integer sumSalary2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(),
                (sum1, sum2) -> sum1 + sum2);
        // 求工资之和方式3:
        Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);
​
        // 求最高工资方式1:
        Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
                Integer::max);
        // 求最高工资方式2:
        Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(),
                (max1, max2) -> max1 > max2 ? max1 : max2);
​
        System.out.println("工资之和:" + sumSalary.get() + "," + sumSalary2 + "," + sumSalary3);
        System.out.println("最高工资:" + maxSalary + "," + maxSalary2);
        
    }
工资之和:49300,49300,49300
最高工资:9500,9500

1.4 注意事项

  • 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
  • 流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)
  • 不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们期望的)

\