当前位置:   article > 正文

java8 新特性之 Stream API 完整使用_avoid mutation using stream api 'sum()' operation

avoid mutation using stream api 'sum()' operation

java8 新特性之 Stream API

一、前言

1、什么是Stream

 Stream 到底是什么
 是数据渠道、用于操作数据源(集合、数组等)、所生成的元素序列
 集合讲的是数据、Stream 讲的是计算
  . Stream 自己不会存储元素
  . Stream 不会改变源对象、相反、他们会返回一个持有结果的新Stream 
  . Stream 操作是延迟执行的、这意味着他们会得到需要结果的时候才执行
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2、测试的数据

想测试 把这个类导入IDEA中引用

public class EmployeeData {
	public static List<Employee> getEmployees(){
		List<Employee> list = new ArrayList<>();
		list.add(new Employee(20001, "马到成功", 34, 6000.38));
		list.add(new Employee(20002, "马不下来", 12, 9876.12));
		list.add(new Employee(20003, "刘狗子", 33, 3000.82));
		list.add(new Employee(20004, "张军雷", 26, 7657.37));
		list.add(new Employee(20005, "老亚瑟", 65, 5555.32));
		list.add(new Employee(20006, "吕布", 42, 9500.43));
		list.add(new Employee(20007, "妲己", 26, 4333.32));
		list.add(new Employee(20008, "被擒虎", 35, 2500.32));
		return list;
	}
	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

二、Stream操作的三个步骤

在这里插入图片描述
在这里插入图片描述

三、创建Stream 的4种方式

1、创建 Stream方式一:通过集合

    @Test
    public void test1() {
        List<Employee> employees = EmployeeData.getEmployees();

//        default Stream<E> stream() : 返回一个顺序流
        Stream<Employee> stream = employees.stream();

//        default Stream<E> parallelStream() : 返回一个并行流
        Stream<Employee> parallelStream = employees.parallelStream();


    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2、创建 Stream方式二:通过数组

    @Test
    public void test2() {
        int[] arr = new int[]{1, 2, 3, 4, 5, 6};
        //调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流
        IntStream stream = Arrays.stream(arr);

        Employee e1 = new Employee(1001, "Tom");
        Employee e2 = new Employee(1002, "Jerry");
        Employee[] arr1 = new Employee[]{e1, e2};
        Stream<Employee> stream1 = Arrays.stream(arr1);

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

3、创建 Stream方式三:通过Stream的of()

    @Test
    public void test3() {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

    }
  • 1
  • 2
  • 3
  • 4
  • 5

4、创建 Stream方式四:创建无限流

    @Test
    public void test4() {

//      迭代
//      public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
        //遍历前10个偶数
        Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);


//      生成
//      public static<T> Stream<T> generate(Supplier<T> s)
        Stream.generate(Math::random).limit(10).forEach(System.out::println);

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

四、筛选与切片

1、操作类

public class EmployeeData {
	public static List<Employee> getEmployees(){
		List<Employee> list = new ArrayList<>();
		list.add(new Employee(20001, "马到成功", 34, 6000.38));
		list.add(new Employee(20002, "马不下来", 12, 9876.12));
		list.add(new Employee(20003, "刘狗子", 33, 3000.82));
		list.add(new Employee(20004, "张军雷", 26, 7657.37));
		list.add(new Employee(20005, "老亚瑟", 65, 5555.32));
		list.add(new Employee(20006, "吕布", 42, 9500.43));
		list.add(new Employee(20007, "妲己", 26, 4333.32));
		list.add(new Employee(20008, "被擒虎", 35, 2500.32));
		return list;
	}
	
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

2、filter 过滤

filter(Predicate p)——接收 Lambda , 从流中排除某些元素。

    @Test
    public void test1(){
        List<Employee> list = EmployeeData.getEmployees();
        //filter(Predicate p)——接收 Lambda , 从流中排除某些元素。
        Stream<Employee> stream = list.stream();
        //练习:查询员工表中薪资大于7000的员工信息
        stream.filter(e -> e.getSalary() > 7000).forEach(System.out::println);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3、limit(n)——截断流,使其元素不超过给定数量

limit(n)——截断流,使其元素不超过给定数量。

    @Test
    public void test1(){
       List<Employee> list = EmployeeData.getEmployees();
          //limit(n)——截断流,使其元素不超过给定数量。
        list.stream().limit(3).forEach(System.out::println);
        System.out.println();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

4、skip(n) —— 跳过元素

skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补

    @Test
    public void test1(){
//skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
        List<Employee> list = EmployeeData.getEmployees();
        list.stream().skip(3).forEach(System.out::println);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

5、distinct 去重操作

distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素

  @Test
    public void test1(){
    //distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
        List<Employee> list = EmployeeData.getEmployees();
        list.add(new Employee(1010,"刘强东",40,8000));
        list.add(new Employee(1010,"刘强东",41,8000));
        list.add(new Employee(1010,"刘强东",40,8000));
        list.add(new Employee(1010,"刘强东",40,8000));
        list.add(new Employee(1010,"刘强东",40,8000));
        list.stream().distinct().forEach(System.out::println);
        
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

五、映射

1、map --收集将元素转换成其他形式或提取信息

map(Function f)——接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。

    @Test
    public void test2(){
        List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
        list.stream().map(str ->   str.toUpperCase()).forEach(System.out::println);
}
  • 1
  • 2
  • 3
  • 4
  • 5

练习1:获取员工姓名长度大于3的员工的姓名。

    @Test
    public void test2(){
        List<Employee> employees = EmployeeData.getEmployees();
        Stream<String> namesStream = employees.stream().map(Employee::getName);
        namesStream.filter(name -> name.length() > 3).forEach(System.out::println);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

练习2:

    @Test
    public void test2(){
     List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
        Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest1::fromStringToStream);
        streamStream.forEach(s ->{
            s.forEach(System.out::println);
        });
        }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2、flatMap 将流中的每个值都换成另一个流

flatMap(Function f) — —接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。

    @Test
    public void test2(){
  //flatMap(Function f)——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
 List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
        Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream);
        characterStream.forEach(System.out::println);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3、排序 sorted()——自然排序

   @Test
    public void test4(){
//        sorted()——自然排序
        List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7);
        list.stream().sorted().forEach(System.out::println);
        //抛异常,原因:Employee没有实现Comparable接口
//        List<Employee> employees = EmployeeData.getEmployees();
//        employees.stream().sorted().forEach(System.out::println);


//        sorted(Comparator com)——定制排序

        List<Employee> employees = EmployeeData.getEmployees();
        employees.stream().sorted( (e1,e2) -> {
           int ageValue = Integer.compare(e1.getAge(),e2.getAge());
           if(ageValue != 0){
               return ageValue;
           }else{
               return -Double.compare(e1.getSalary(),e2.getSalary());
           }

        }).forEach(System.out::println);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

六、Stream的终止操作

1、allMatch(Predicate p) 是否匹配所有元素

检查是否匹配所有元素。

    @Test
    public void test1(){
        List<Employee> employees = EmployeeData.getEmployees();
//        allMatch(Predicate p)——检查是否匹配所有元素。
//          练习:是否所有的员工的年龄都大于18
        boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
        System.out.println(allMatch);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2、anyMatch(Predicate p) 是否至少匹配一个元素

检查是否至少匹配一个元素。

    @Test
    public void test2(){
        List<Employee> employees = EmployeeData.getEmployees();
        // 练习:是否存在员工的工资大于 10000
        boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000);
        System.out.println(anyMatch);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3、noneMatch(Predicate p) 是否至少匹配一个元素

检查是否至少匹配一个元素。

    @Test
    public void test2(){
        List<Employee> employees = EmployeeData.getEmployees();
      //练习:是否存在员工姓“雷”
        boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));
        System.out.println(noneMatch);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

4、findFirst(Predicate p) 返回第一个元素

返回第一个元素

    @Test
    public void test2(){
        List<Employee> employees = EmployeeData.getEmployees();
//        findFirst——返回第一个元素
        Optional<Employee> employee = employees.stream().findFirst();
        System.out.println(employee);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

5、findAny 返回当前流中的任意元素

返回当前流中的任意元素

    @Test
    public void test2(){
        List<Employee> employees = EmployeeData.getEmployees();
           //findAny——返回当前流中的任意元素
        Optional<Employee> employee1 = employees.parallelStream().findAny();
        System.out.println(employee1);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

6、count 返回流中元素的总个数

返回流中元素的总个数

    @Test
    public void test2(){
        List<Employee> employees = EmployeeData.getEmployees();
        // count——返回流中元素的总个数
        long count = employees.stream().filter(e -> e.getSalary() > 5000).count();
        System.out.println(count);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

7、max(Comparator c) 返回流中最大值

max(Comparator c)——返回流中最大值

    @Test
    public void test2(){
        List<Employee> employees = EmployeeData.getEmployees();
        //练习:返回最高的工资:
        Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());
        Optional<Double> maxSalary = salaryStream.max(Double::compare);
        System.out.println(maxSalary);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

8、min(Comparator c) 返回流中最小值

返回流中最小值

    @Test
    public void test2(){
        List<Employee> employees = EmployeeData.getEmployees();
        //练习:返回最低工资的员工
        Optional<Employee> employee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(employee);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

七、reduce 规约

1、reduce(T identity, BinaryOperator) 可以将流中元素反复结合起来

可以将流中元素反复结合起来,得到一个值。返回 T

    @Test
    public void test3(){
    // reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T
    // 练习1:计算1-10的自然数的和
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        Integer sum = list.stream().reduce(0, Integer::sum);
        System.out.println(sum);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2、reduce(T identity, BinaryOperator)

可以将流中元素反复结合起来,得到一个值。返回 T

    @Test
    public void test3(){
       //reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
       //练习2:计算公司所有员工工资的总和
        List<Employee> employees = EmployeeData.getEmployees();
        Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
       // Optional<Double> sumMoney = salaryStream.reduce(Double::sum);
        Optional<Double> sumMoney = salaryStream.reduce((d1,d2) -> d1 + d2);
        System.out.println(sumMoney.get());

    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

八、collect(Collector c) 收集

1、collect(Collector c) 收集成List

//collect(Collector c)——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法

    @Test
    public void test3(){

            //练习1:查找工资大于6000的员工,结果返回为一个List或Set
        List<Employee> employees = EmployeeData.getEmployees();
        List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());
        employeeList.forEach(System.out::println);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2、collect(Collector c) 收集成Set

//collect(Collector c)——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法

    @Test
    public void test3(){
         //练习1:查找工资大于6000的员工,结果返回为一个List或Set
   Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
        employeeSet.forEach(System.out::println);
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

九、Optional 类

Optional 类(java.util.Optional) 是一个容器,他可以保存类型的T值,代表这个值的存在,或者仅仅保存null,表示这个值不存在,原来用null表示的值不存在,现在Optional 可以更好地表达这个概念,并且可以避免null指针

1、创建两个类

public class Boy {
    private Girl girl;

    @Override
    public String toString() {
        return "Boy{" + "girl=" + girl + '}';
    }

    public Girl getGirl() {
        return girl;
    }

    public void setGirl(Girl girl) {
        this.girl = girl;
    }

    public Boy() {

    }

    public Boy(Girl girl) {

        this.girl = girl;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
public class Girl {

    private String name;

    @Override
    public String toString() {
        return "Girl{" +
                "name='" + name + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Girl() {

    }

    public Girl(String name) {

        this.name = name;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

2、of(T t):保证t是非空的

    @Test
    public void test1(){
        Girl girl = new Girl();
        //of(T t):保证t是非空的
        Optional<Girl> optionalGirl = Optional.of(girl);
        System.out.println(optionalGirl);

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3、ofNullable(T t):t可以为null

    @Test
    public void test2(){
        Girl girl = new Girl();
        girl = null;
        //ofNullable(T t):t可以为null
        Optional<Girl> optionalGirl = Optional.ofNullable(girl);
        System.out.println(optionalGirl);
        //orElse(T t1):如果单前的Optional内部封装的t是非空的,则返回内部的t.
        //如果内部的t是空的,则返回orElse()方法中的参数t1.
        Girl girl1 = optionalGirl.orElse(new Girl("赵丽颖"));
        System.out.println(girl1);

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

4、为何使用演示1

展示空指针

    public String getGirlName(Boy boy){
        return boy.getGirl().getName();
    }

    @Test
    public void test3(){
        Boy boy = new Boy();
        boy = null;
        String girlName = getGirlName(boy);
        System.out.println(girlName);

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

5、为何使用演示2

原生的优化空指针

    //优化以后的getGirlName():
    public String getGirlName1(Boy boy){
        if(boy != null){
            Girl girl = boy.getGirl();
            if(girl != null){
                return girl.getName();
            }
        }

        return null;

    }

    @Test
    public void test4(){
        Boy boy = new Boy();
        boy = null;
        String girlName = getGirlName1(boy);
        System.out.println(girlName);

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

6、使用Optional类的getGirlName():

使用Optional优化上述两个为何使用Optional 作为判空操作

    //使用Optional类的getGirlName():
    public String getGirlName2(Boy boy){

        Optional<Boy> boyOptional = Optional.ofNullable(boy);
        //此时的boy1一定非空
        Boy boy1 = boyOptional.orElse(new Boy(new Girl("迪丽热巴")));

        Girl girl = boy1.getGirl();

        Optional<Girl> girlOptional = Optional.ofNullable(girl);
        //girl1一定非空
        Girl girl1 = girlOptional.orElse(new Girl("古力娜扎"));

        return girl1.getName();
    }

    @Test
    public void test5(){
        Boy boy = null;
        boy = new Boy();
        boy = new Boy(new Girl("苍老师"));
        String girlName = getGirlName2(boy);
        System.out.println(girlName);

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

7、Optional.empty() : 创建一个空的 Optional 实例

通过Optional.empty() 构造一个null对象

    @Test
    public void test7(){
        Optional<Boy> empty = Optional.empty();
          System.out.println(empty); //空值 empty.get() 报错空指针
        Boy boy = empty.orElse(new Boy(new Girl("张三")));
        System.out.println(boy);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/367361
推荐阅读
相关标签
  

闽ICP备14008679号