Java中的Stream流详解

1、Stream API概述

  • Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。
  • 使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询,也可以使用 Stream API 来并行执行操作。
  • 简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。
  • 所有API都在java.util.stream.*下;

流(Stream) 到底是什么呢?

  • 是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列;
  • 集合讲的是数据,流讲的是计算!
  • IO流操作的是文件,是字节数据的流动;Stream流操作的是集合或者数组,也就是容器中的元素,更加方便;
  • 通过容器关联了一个Stream流;
  • 注意:

①Stream 自己不会存储元素。
②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

  • 为什么提供他?

它的出现其实就是为了我们能更加方便对集合中元素进行操作,以前我们对集合中元素操作,需要遍历集合,然后进行逻辑判断,学习完Stream流会发现很简单;

2、Stream 的操作三个步骤

  • 创建 Stream

    一个数据源(如:集合、数组),获取一个流;

  • 中间操作

    一个中间操作链,对数据源的数据进行处理;

中间操作包括过滤、切片、排序等一些中间环节;

  • 终止操作(终端操作)

    一个终止操作,执行中间操作链,并产生结果;

3、创建Stream的方式

方式1:

  • Java8 中的 Collection 接口被扩展,提供了两个获取流的方法:
  • 首先一定要有一个容器;

default Stream stream()

  • 返回一个序列 Stream与集合的来源。

default Stream parallelStream()

  • 返回一个可能并行 Stream与集合的来源,这种方法返回一个连续的流。
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class MyTest1 {
    public static void main(String[] args) {
        //首先要有一个容器
        List<Integer> list = Arrays.asList(20, 32, 12, 34, 54);
        //通过集合中的方法来获取一个Stream流
        Stream<Integer> stream = list.stream();
        //当然,你现在打印的肯定只是地址值
        System.out.println(stream);
        //java.util.stream.ReferencePipeline$Head@677327b6
    }
}

方式2:

  • Java8 中的 Arrays 的静态方法 stream() 可以获取数组流:
  • 首先一定要有一个容器;

static Stream stream(T[] array):

  • 返回一个流,重载形式,能够处理对应基本类型的数组:

public static IntStream stream(int[] array)
public static LongStream stream(long[] array)
public static DoubleStream stream(double[] array)

import java.util.Arrays;
import java.util.stream.Stream;

public class MyTest2 {
    public static void main(String[] args) {
        Integer[] arr={78,23,23,53,24};
        Stream<Integer> stream = Arrays.stream(arr);
    }
}

方式3:

  • 由值创建流,可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。

public static Stream of(T… values) : 返回一个流

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class MyTest3 {
    public static void main(String[] args) {
        //方式1:
        Stream<Integer> stream = Stream.of(21, 6, 23, 12, 89, 1);

        //方式2:
        List<Integer> list = Arrays.asList(21, 6, 23, 12, 89, 1);
        Stream<List<Integer>> stream1 = Stream.of(list);
    }
}

方式4:

  • 由函数创建流:创建无限流可以使用静态方法 Stream.iterate()Stream.generate()

public static Stream iterate(final T seed, finalUnaryOperator f) 迭代
public static Stream generate(Supplier s) 生成

import java.util.stream.Stream;
public class MyTest4 {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.iterate(1, num -> num + 1);
        //中间操作
        Stream<Integer> stream1 = stream.limit(5);
        //终止操作
        stream1.forEach(System.out::println);
        /*1
        2
        3
        4
        5*/
    }
}
import java.util.stream.Stream;
public class MyTest5 {
    public static void main(String[] args) {
        //获取无限流
        Stream<Double> generate = Stream.generate(() -> {
            double random = Math.random();
            return random;
        });
        //中间操作
        Stream<Double> limit1 = generate.limit(10);

        //终止操作
        limit1.forEach(System.out::println);
        /*0.6583484943109231
        0.10882799952015698
        0.6116663593491921
        0.11630531827789004
        0.0879125613673647
        0.9139497996838213
        0.28944118771182126
        0.5863308008246001
        0.06331586074061579
        0.277708755661223*/
    }
}

4、中间操作

  • 多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!
  • 而在终止操作时一次性全部处理,称为“惰性求值”。
  • 中间操作分为以下几种:

筛选与切片

方法名方法作用
filter(Predicate p)过滤,接收 Lambda,从流中排除某些元素
distinct()去重,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
limit(long maxSize)截断流,使其元素不超过给定数量
skip(long n)跳过元素,返回一个扔掉了前 n 个元素的流;若流中元素不足 n 个,则返回一个空流,与 limit(n) 互补

代码示例:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class MyTest1 {
    public static void main(String[] args) {
        //使用Stream流分三个步骤
        //1.获取一个Stream流,来关联一个容器。
        //2.进行中间环节的操作,来得到一个持有新结果的流
        //3.进行终止操作,来得到我们的结果,但是不会对原有的容器有任何改变

        //1.需要有一个容器
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );

        //1、获取Stream流来关联集合
        Stream<Employee> stream = list.stream();
        //2、中间操作:返回一个持有新结果的流
        //filter(Predicate p)————过滤、接收 Lambda ,从流中排除某些元素。
        //获取工资大于6000员工
        Stream<Employee> employeeStream = stream.filter(employee -> {
            //如果返回false 就是不符合条件 返回true 就是符合
            return employee.getSalary() > 6000;
        });

        //3、终止操作
        employeeStream.forEach(System.out::println);
        /*Employee [id=102, name=李四, age=59, salary=6666.66, status=null]
        Employee [id=101, name=张三, age=18, salary=9999.99, status=null]
        Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]
        Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]
        Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]*/

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

        //以上操作可以链式编程
        list.stream().filter(employee ->employee.getSalary() > 6000).forEach(System.out::println);

        //可以过滤出姓赵的员工
        list.stream().filter(e->e.getName().startsWith("赵")).forEach(System.out::println);
        /*Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]
        Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]
        Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]*/
    }
}
import java.util.Arrays;
import java.util.List;

public class MyTest2 {
    public static void main(String[] args) {
        // distinct() 去重,需要元素 重写hashCode()和equals()方法
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),  //0x001
                new Employee(104, "赵六", 8, 7777.77),   //0x002
                new Employee(105, "田七", 38, 5555.55)   //0x003
        );
       
        //流持有容器中的数据---->过滤中间操作(返回一个持有新结果的流)--->中间操作过滤(返回一个持有新结果的流)--->终止操作(遍历持有新结果的流)
        list.stream().filter(employee -> employee.getSalary() > 6000).distinct().forEach(System.out::println);
        /*Employee [id=102, name=李四, age=59, salary=6666.66, status=null]
        Employee [id=101, name=张三, age=18, salary=9999.99, status=null]
        Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]*/
    }
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class MyTest3 {
    public static void main(String[] args) {
         /*  limit( long maxSize)截断流,使其元素不超过给定数量。
        skip( long n)跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit (n) 互补*/

        List<Integer> list = Arrays.asList(10, 20, 30, 40, 50);
        Stream<Integer> stream = list.stream();
        //获取元素大于30
        Stream<Integer> integerStream = stream.filter(integer -> integer > 30);
        //limit(1); 从头开始截断几个
        Stream<Integer> limit = integerStream.limit(3);
        limit.forEach(System.out::println);
        /*
        * 40
        * 50
        * */

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

        //1、容器有了
        List<Employee> list2 = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );

        //获取年龄大于20的员工
        list2.stream().filter(employee -> employee.getAge() > 20).limit(1).forEach(System.out::println);
        //Employee [id=102, name=李四, age=59, salary=6666.66, status=null]
    }
}
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class MyTest4 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(10, 20, 30, 40, 50);
        Stream<Integer> stream = list.stream();
        //获取元素大于30
        Stream<Integer> integerStream = stream.filter(integer -> integer > 30);
        //skip(1) 跳过前1个不要,取后面剩下的,跟limit()互补
        Stream<Integer> skip = integerStream.skip(1);
        skip.forEach(System.out::println);
        //50

        //注意;终止操作不执行,中间环节就不执行,体现的就是一种延迟加载的思想,你要用的时候,我再去操作

        List<Integer> list2 = Arrays.asList(10, 20, 30, 40, 50);
        Stream<Integer> stream1 = list2.stream();
        //中间操作
        Stream<Integer> integerStream1 = stream1.filter(new Predicate<Integer>() {
            @Override
            public boolean test(Integer integer) {
                System.out.println("中间环节进行了");
                return integer > 10;
            }
        });

        //遍历 :终止操作
        integerStream1.forEach(System.out::println);
        /*中间环节进行了
        中间环节进行了
        20
        中间环节进行了
        30
        中间环节进行了
        40
        中间环节进行了
        50*/
    }
}

映射

方法名方法作用
map(Function f)接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap(Function f)接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
mapToDouble(ToDoubleFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
mapToInt(ToIntFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。
mapToLong(ToLongFunction f)接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。
import org.westos.demo2.Employee;

import java.util.Arrays;
import java.util.List;

public class MyTest {
    public static void main(String[] args) {
        // map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
        //提前集合中的元素,应用到一个方法上。
        List<Employee> list2 = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );

        //以上几步,链式编程
        list2.stream().distinct().map(employee -> employee.getName()).forEach(System.out::println);
        /*李四
        张三
        王五
        赵六
        田七*/
    }
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class MyTest1 {
    public static void main(String[] args) {

        List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd");
        //把集合中的元素变大写
        Stream<String> stream = list.stream();
        //map:提取集合中的元素,应用到一个方法上
        Stream<String> stringStream = stream.map(s -> s.toUpperCase());
        stringStream.forEach(System.out::println);

        //以上可写成链式编程
        // list.stream().map(s -> s.toUpperCase()).forEach(System.out::println);
        /*AAA 
        BBB
        CCC
        DDD*/
    }
}

需求:提取集合中的每一个元素,把这个字符串,截取成一个个字符,放到换一个集合中,在把这个集合转换成Stream流返回;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;

public class MyTest3 {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("aaa", "bbb", "ccc", "ddd");

        //"aaa" --->'a' 'a' 'a' ---> ['a','a','a']--->流

        Stream<String> stream = list.stream();
        Stream<Stream<Character>> objectStream = stream.map(new Function<String, Stream<Character>>() {
            @Override
            public Stream<Character> apply(String s) {
                //System.out.println(s);
                // 提取集合中的每一个元素,把这个字符串,截取成一个个字符,放到一个集合中,在把这个集合转换成Stream流返回。
                //这个操作,没有现成方法可用,那我们自己就编写一个
                return getStreamChar(s);
            }


        });
        //终止操作 遍历每一个字符
        objectStream.forEach(new Consumer<Stream<Character>>() {
            @Override
            public void accept(Stream<Character> characterStream) {
                characterStream.forEach(character -> System.out.print(character + "\t"));
            }
        });
        //a    a	a	b	b	b	c	c	c	d	d	d	

        System.out.println("\n" + "===================================");
        //flatMap(Function f)————————接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流.
        //用flatMap来做一下

        List<String> list2 = Arrays.asList("aaa", "bbb", "ccc", "ddd");

        //提取集合中的每一个元素,把这个字符串,截取成一个个字符,放到换一个集合中,在把这个集合转换成Stream流返回。
        Stream<String> stream1 = list2.stream();
        Stream<Character> characterStream = stream1.flatMap(new Function<String, Stream<Character>>() {
            @Override
            public Stream<Character> apply(String s) {
                return getStreamChar(s);
            }
        });
        characterStream.forEach(character -> System.out.print(character + "\t"));
        //a	 a	a	b	b	b	c	c	c	d	d	d
    }

    private static Stream<Character> getStreamChar(String s) {
        //"aaa"
        ArrayList<Character> arrayList = new ArrayList<>();
        for (char c : s.toCharArray()) {
            arrayList.add(c);
        }
        Stream<Character> stream = arrayList.stream();

        return stream;
    }
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class MyTest4 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(200, 30, 20);
        Stream<Integer> stream = list.stream();
        IntStream intStream = stream.mapToInt(value -> (int) Math.pow(value, 2));
        intStream.forEach(value -> System.out.println(value));
//        40000
//        900
//        400
    }
}

排序

方法名方法作用
sorted()产生一个新流,其中按自然顺序排序 元素实现Compareble接口
sorted(Comparator comp)产生一个新流,其中按比较器顺序排序 传入一个比较
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class MyTest5{
    public static void main(String[] args) {
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );
        //按年龄大小来排序
        Stream<Employee> stream = list.stream();
        //自然排序要求元素实现一个Compareble接口
        //stream.sorted()
        //使用比较器排序
        Stream<Employee> stream1 = stream.sorted((e1, e2) -> e1.getAge() - e2.getAge());
        stream1.forEach(System.out::println);
        /*Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]
        Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]
        Employee [id=104, name=赵六, age=8, salary=7777.77, status=null]
        Employee [id=101, name=张三, age=18, salary=9999.99, status=null]
        Employee [id=103, name=王五, age=28, salary=3333.33, status=null]
        Employee [id=105, name=田七, age=38, salary=5555.55, status=null]
        Employee [id=102, name=李四, age=59, salary=6666.66, status=null]*/
    }
}

5、终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void;

查找与匹配

allMatch(Predicate p)
检查是否匹配所有元素,比如判断所有员工的年龄都是17岁,如果有一个不是,就返回false;
anyMatch(Predicate p)
检查是否至少匹配一个元素,比如判断是否有姓王的员工,如果至少有一个就返回true;
noneMatch(Predicate p)
检查是否没有匹配所有元素 employee.getSalary() < 3000; 每个员工的工资如果都高于3000就返回true 如果有一个低于3000 就返回false
findFirst()
返回第一个元素,比如获取工资最高的人或者获取工资最高的值
findAny()
返回当前流中的任意元素,比如随便获取一个姓王的员工
count()
返回流中元素总数
max(Comparator c)
返回流中最大值,比如:获取最大年龄值
min(Comparator c)
返回流中最小值,比如:获取最小年龄的值
forEach(Consumer c)
内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做了)

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class MyTest {
    public static void main(String[] args) {
        //终止操作,当我们执行完了中间环节,就想要执行终止操作,来得到中间环节流持有的结果
        //终止操作中,最常用的一个操作,就是遍历,forEach();
        //有的时候,并不是只想打印看,我们是想要获取中间环节操作完之后的结果。

        // allMatch(Predicate p) 检查是否匹配所有元素 比如判断 所有员工的年龄都是17岁 如果有一个不是, 就返回false
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );

        Stream<Employee> stream = list.stream();

        //终止操作
        boolean b = stream.allMatch(new Predicate<Employee>() {
            @Override
            public boolean test(Employee employee) {
                return employee.getAge() == 17;
            }
        });
        System.out.println(b);//false

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

        //中间操作。把所有年龄提取出出来  15 28 36
        Stream<Employee> stream2 = list.stream();

        Stream<Integer> integerStream = stream2.map(new Function<Employee, Integer>() {
            @Override
            public Integer apply(Employee employee) {
                return employee.getAge();
            }
        });
        //终止操作做判断
        boolean b1 = integerStream.allMatch(new Predicate<Integer>() {
            @Override
            public boolean test(Integer integer) {
                return integer == 17;
            }
        });

        System.out.println(b1);//false
    }
}
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class MyTest2 {
    public static void main(String[] args) {
        // anyMatch(Predicate p) 检查是否至少匹配一个元素 比如判断是否有姓王的员工, 如果至少有一个就返回true
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 5555.55)
        );

        //判断他们的工资有没有人高于7000 只有一个人高于7000 都返回true
        boolean b = list.stream().anyMatch(new Predicate<Employee>() {
            @Override
            public boolean test(Employee employee) {
                return employee.getSalary() > 7000;
            }
        });
        System.out.println(b);//true
    }
}
import java.util.Arrays;
import java.util.List;

public class MyTest3 {
    public static void main(String[] args) {
        //  noneMatch(Predicate p) 检查是否没有匹配所有元素
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 0.55)
        );
        //noneMatch()  employee.getSalary() < 3000; 每个员工的工资如果都高于3000就返回true 如果有一个低于3000 就返回false
        boolean b = list.stream().noneMatch(employee -> employee.getSalary() < 3000);
        System.out.println(b);
        //false
    }
}
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class MyTest {
    public static void main(String[] args) {
        List<Employee> list = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "张三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 0.55)
        );

        // findFirst() 返回第一个元素 比如获取工资最高的人 或者 获取工资最高的值是
        //我要获取工资最高的那个员工Employee
        // Optional 容器,会把员工放到这个容器中
        Optional<Employee> first = list.stream().sorted((e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary())).findFirst();
        Employee employee = first.get();
        System.out.println(employee);
        //Employee [id=101, name=张三, age=18, salary=9999.99, status=null]
        System.out.println("====================================");
        //我要获最高工资  9999.99

        Optional<Double> first1 = list.stream().map(e -> e.getSalary()).sorted((a, b) -> (int) (b-a)).findFirst();
        Double aDouble = first1.get();
        System.out.println(aDouble);
        //9999.99
    }
}

归约

reduce(T iden, BinaryOperator b)

  • 参1 是起始值, 参2 二元运算 可以将流中元素反复结合起来,得到一个值。返回 T 比如: 求集合中元素的累加总和

reduce(BinaryOperator b)

  • 这个方法没有起始值,可以将流中元素反复结合起来,得到一个值。返回 Optional , 比如你可以算所有员工工资的总和;备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它来进行网络搜索而出名。
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class MyTest3 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(20, 30, 50, 200);

      /*  reduce(T iden, BinaryOperator b) 参1 是起始值, 参2 二元运算 可以将流中元素反复结合起来,得到一个值。返回 T 比如:
        求集合中元素的累加总和*/
        Optional<Integer> reduce = list.stream().reduce((a, b) -> a + b);
        Integer integer = reduce.get();
        System.out.println(integer);//300

        System.out.println("===========================================");
        //参数1:你可以给一个起始值
        Integer reduce1 = list.stream().reduce(0, (a, b) -> a + b);
        System.out.println(reduce1);//300

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


        List<Employee> list2 = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 0.55)
        );

        //求员工总工资
        Double reduce2 = list2.stream().map(employee -> employee.getSalary()).reduce(0.0, (a, b) -> a + b);
        System.out.println(reduce2);//106667.11000000002
    }
}

收集

collect(Collector c)
将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法;Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map);但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例;

Collectors 中的方法

List<T> toList()
把流中元素收集到List 比如把所有员工的名字通过map()方法提取出来之后,在放到List集合中去;
Set<T> toSet()
把流中元素收集到Set 比如把所有员工的名字通过map()方法提取出来之后,在放到Set集合中去
Collection<T> toCollection()
把流中元素收集到创建的集合 比如把所有员工的名字通过map()方法提取出来之后,在放到自己指定的集合中去
Long counting()
计算流中元素的个数
Integer summingInt()
对流中元素的整数属性求和
Double averagingInt()
计算流中元素Integer属性的平均值
IntSummaryStatistics summarizingInt()
收集流中Integer属性的统计值。
String joining()
连接流中每个字符串 比如把所有人的名字提取出来,在通过"-"横杠拼接起来
Optional<T> maxBy()
根据比较器选择最大值 比如求最大工资
Optional<T> minBy()
根据比较器选择最小值 比如求最小工资
归约产生的类型 reducing()从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值
转换函数返回的类型 collectingAndThen()
包裹另一个收集器,对其结果转换函数
Map<K, List<T>> groupingBy()
根据某属性值对流分组,属性为K,结果为V 比如按照 状态分组
Map<Boolean, List<T>> partitioningBy()
根据true或false进行分区 比如 工资大于等于6000的一个区,小于6000的一个区

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MyTest {
    public static void main(String[] args) {
        //收集流中的结果
        List<Employee> list2 = Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 0.55)
        );

        Stream<String> stringStream = list2.stream().map(e -> e.getName()).distinct();
        // stringStream.forEach(System.out::println);
        // Collector<Object, ?, List<Object>> objectListCollector = Collectors.toList();
        //把结果收集到List集合
        List<String> collect = stringStream.collect(Collectors.toList());
        System.out.println(collect);
        //[李四, 王三, 王五, 王六, 赵六, 田七]

        //把结果收集到Set集合
        Stream<String> stringStream2 = list2.stream().map(e -> e.getName()).distinct();
        Set<String> collect1 = stringStream2.collect(Collectors.toSet());
        System.out.println(collect1);
        //[王三, 李四, 王五, 赵六, 王六, 田七]

        //收集到指定集合里面
        Stream<String> stringStream3 = list2.stream().map(e -> e.getName()).distinct();
        LinkedHashSet<String> collect2 = stringStream3.collect(Collectors.toCollection(LinkedHashSet::new));
        System.out.println(collect2);
        //[李四, 王三, 王五, 王六, 赵六, 田七]

        //求平均工资

        Double collect3 = list2.stream().collect(Collectors.averagingDouble(e -> e.getSalary()));
        System.out.println(collect3);
        //7619.079285714286

        System.out.println("======================================");
        String collect4 = list2.stream().map(Employee::getName).collect(Collectors.joining("-"));
        System.out.println(collect4);
        //李四-王三-王三-王三-王三-王三-王五-王六-王六-王六-王六-赵六-赵六-田七

        String collect5 = list2.stream().map(Employee::getName).collect(Collectors.joining(",","[","]"));
        System.out.println(collect5);
        //[李四,王三,王三,王三,王三,王三,王五,王六,王六,王六,王六,赵六,赵六,田七]
    }
}
import java.util.*;
import java.util.stream.Collectors;

public class MyTest2 {
    public static void main(String[] args) {
        //请平均工资,求总工资,求最高工资,最低工资
        List<Employee> list= Arrays.asList(
                new Employee(102, "李四", 59, 6666.66),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(101, "王三", 18, 9999.99),
                new Employee(103, "王五", 28, 3333.33),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "王六", 17, 7777.77),
                new Employee(104, "赵六", 8, 7777.77),
                new Employee(104, "赵六", 17, 7777.77),
                new Employee(105, "田七", 38, 0.55)
        );
        DoubleSummaryStatistics collect = list.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
        double max = collect.getMax();
        double min = collect.getMin();
        double average = collect.getAverage();
        double sum = collect.getSum();
        long count = collect.getCount();

        System.out.println(max);//9999.99
        System.out.println(min);//0.55
        System.out.println(average);//7619.079285714286
        System.out.println(sum);//106667.11
        System.out.println(count);//14

        System.out.println("=============================");
        Optional<Employee> collect1 = list.stream().collect(Collectors.maxBy((e1, e2) -> (int) (e1.getSalary() - e2.getSalary())));
        Employee employee = collect1.get();
        System.out.println(employee);
        //Employee [id=101, name=王三, age=18, salary=9999.99, status=null]

        Optional<Double> collect2 = list.stream().map(Employee::getSalary).collect(Collectors.minBy((a, b) -> (int) (a - b)));
        System.out.println(collect2.get());//0.55
    }
}
  • 15
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值