Java基础 Java8新特性

目录:

1、Lambda表达式

2、函数式(Functional)接口

3、方法引用与构造器引用

4、强大的Stream API

5、Optional类

学习思维方式:

1、大处着眼,小处着手

2、逆向思维,反证法

3、透过问题看本质

两句话:

1、小不忍则乱大谋

2、识时务者为俊杰

Java8新特性简介:

速度更快

代码更少(增加了新的语法:Lambda表达式)

强大的Stream API

便于并行

最大化减少空指针异常:Optional

Nashorn引擎,允许在JVM上运行JS应用

并行流与串行流

并行流就是把一个内容分成多个数据块,并用不同的线程分别 处理每个数据块的流。相比较串行的流,并行的流可以很大程度上提高程序 的执行效率

Java8中将并行进行了优化,我们可以很容易的对数据进行并行操作

Stream API可以声明性地通过parallel()与sequential()在并行流与顺序流之间里德切换

16-1 Lambda表达式

为什么使用Lambda表达式

Lambda是一个匿名函数,我们可以把Lambda表达式理解 为是一段可以传递的代码(将代码像数据一样进行传递)。使用它可以写出更简洁、更灵活的代码。作为一种更肾源的代码风格,使Java的语言表达能力得到了提升

前提,使用的对象有且只有一个抽象方法

package lambda_;

import org.junit.Test;

import java.util.Comparator;

/**
 * @author 黄石杨  on 2022/4/9
 * @version 1.0
 */
public class LambdaTest {

    @Test
    public void test1(){
        Runnable r1 = new Runnable(){
            public void run(){
                System.out.println("我爱北京");
            }
        };
        r1.run();
        System.out.println("**************************");

        Runnable r2 = () ->{
                System.out.println("我爱北京");
        };
        r2.run();
    }

    @Test
    public void test2(){
        Comparator<Integer> com1 = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1,o2);
            }
        };
        int compare1 = com1.compare(12,21);
        System.out.println(compare1);
        //Lambda表达式的写法
        System.out.println("****************");
        Comparator<Integer> com2 = (o1,o2) -> Integer.compare(o1,o2);
        int compare2 = com2.compare(32,21);
        System.out.println(compare2);
        //方法引用
        System.out.println("****************");
        Comparator<Integer> com3 = Integer :: compare;
        int compare3 = com3.compare(32,21);
        System.out.println(compare3);
    }
}
package lambda_;

import org.junit.Test;

import java.util.Comparator;
import java.util.function.Consumer;

/**
 * Lambda表达式的使用
 * 1、举例:(o1,o2) -> Integer.compare(o1,o2);
 * 2、格式:
 *      -> : lambda操作符或箭头操作符
 *      -> 左边: lambda形参列表(其实就是接口中的抽象 方法的形参列表)
 *      -> 右边:lambda体(其实就是重写的抽象方法的方法体)
 * 3、Lambda表达式的使用:(分为 6种情况介绍)
 *  总结:
 *  ->左边:形参列表的参数类型可以省略(类型推断):如果参数列表只有一个参数,其一对()也可以省略
 *  -> 右边:lambda体应该使用一对{}包裹;如果lambda体只有一条执行语句(可以是return语句),省略这一对{}
 *
 * 4、Lambda表达式的本质:作为接口的实例
 * 5、如果一个接口中,只声明了一个抽象方法,则此接口就称为函数式接口
 *
 *
 * @author 小黄debug  on 2022/4/9
 * @version 1.0
 */
public class LambdaTest1 {
    //语法格式一:无参,无返回值
    Runnable r2 = () -> System.out.println("我爱北京");

    //语法格式二:Lambda需要一个参数,但是没有返回值
    @Test
    public void test2(){
        Consumer<String> con = new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };
        con.accept("普通形式");
        System.out.println("***************");
        Consumer<String> con1 = (String s) ->{
            System.out.println(s);
        };
        con1.accept("听与说");
    }

    //语法格式三:数据类型可以活力,因为可由编译器推断得出,称为“类型推断”
    @Test
    public void test3(){
        Consumer<String> con1 = (s) ->{
            System.out.println(s);
        };
        con1.accept("类型推断");
    }

    //语法格式四:Lambda若只需要一个参数时,参数的小括号可以省略
    @Test
    public void test5(){
        Consumer<String> con1 = s ->{
            System.out.println(s);
        };
        con1.accept("只有一个参数,括号也能省");
    }
    //语法格式五:Lambda需要两个或两个以上参数,多条执行语句,并且可以有返回值
    @Test
    public void test6(){
        Comparator<Integer> com2 = (o1, o2) ->{
          return o1.compareTo(o2);
        };
        com2.compare(33,22);
    }
    //语法格式六,当Lambda体只有条语句时,return与大括号若有,都可以省略
    @Test
    public void test7(){
        Comparator<Integer> com2 = (o1, o2) -> o1.compareTo(o2);
        com2.compare(30,45);
    }
}

什么是函数式接口

只包含一个抽象方法的接口,称为函数式接口

你可以通过Lambda表达式来创建该接口的对象。(若Lambda表达式抛出一个受检异常(即:非运行时异常),那么该异常需要在目标接口的抽象方法上进行声明

我们可以在一个接口上使用@FunctionalInterface注解,这样做可以检查它是否是一个函数式接口。同时javadoc也会包含这一条声明,说明这个接口是一个函数式接口。

在java.util.function包下定义了Java8的丰富的函数式接口

如何理解函数式接口

Java从诞生之日起就一直倡导“一切皆对象”,在Java里面面向对象(OOP)

编程是一切,但是随着python、scala等语言的兴起和新技术的挑战,Java不得不做出调整以便支持更加广泛的技术要求,也即Java不但可以支持OOP还可以支持OOF(面向陈洁灵编程)

在函数式编程语言当中,函数被当做一等公民对待,在将函数作为一等公民的编程语言中,Lambda表达式的类型是函数。但是在Java8中,有所不同,在Java8中,Lambda表达式是对象,而不是函数,它们需要依附于一类特别的对象类型------函数式接口

简单的说,在Java8中,Lambda表达式是一个函数式接口的实例。这就是Lambda表达式和函数式接口的关系。也就是说,只要一个对象是函数式接口的实例,那么该对象就可以用Lambda表达式来表示 。

所以以前用匿名实现类的现在都可以用Lambda表达式来写。

lambda表达式中的::

::前        调用的类

::后        调用的具体的方法

package lambda_;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * java内置的4大核心函数式接口
 * 消费型接口Consumer<T> void accept(T t)
 * 供给型接口Supplier<T> T get()
 * 函数型接口Function<T,R> R apply(T t)
 * 断定型接口Predicate<T> boolean test(T t)
 * @author 小黄debug  on 2022/4/9
 * @version 1.0
 */
public class LambdaTest2 {

    @Test
    public void test1(){
        happTime(500, new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("学习太累了,去天上人间买了瓶矿泉水,价格为:"+aDouble+"元");
            }
        });

        happTime(500,(aDouble)->{
            System.out.println("学习太累了,去天上人间买了瓶矿泉水,价格为:"+aDouble+"元");
        });

    }
    public void happTime(double money, Consumer<Double> con){
        con.accept(money);
    }

    @Test
    public void test2(){
        List<String> list = Arrays.asList("北京","南京","天津","东京","普京","西津");
        List<String> filterStrs = filterString(list, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.contains("京");
            }
        });
        System.out.println(filterStrs);

        List<String> filterStrs1 = filterString(list, s -> {
            return s.contains("京");
        });
        System.out.println(filterStrs1);
    }
    //根据给定的规则,过滤集合中的字符串。此规则 由Predicate的方法决定
    public List<String> filterString(List<String> list, Predicate<String> pre){
        ArrayList<String> filterList = new ArrayList<>();
        for (String s : list){
            if(pre.test(s)){
                filterList.add(s);
            }
        }
        return filterList;
    }
}
package lambda_;

import org.junit.Test;

import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 方法引用的使用
 * 1、使用情境:当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
 * 2、方法引用,本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以方法引用,也是函数式接口的实例。
 * 3、使用格式:类(或对象)::方法名
 * 4、具体分为如下三种情况
 *      情况1     对象::非静态方法(实例方法)
 *      情况2     类::静态方法
 *      情况3     类::非静态方法
 *
 * 5、方法引用使用的要求:要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回类值类型相同!(针对情况1和情况2)
 *
 * @author 小黄debug  on 2022/4/9
 * @version 1.0
 */
public class MethodRefTest {

    //情况一:对象::实例方法
    //Consumer 中的void accept(T t)
    //PrintStream中的void println(T t)
    @Test
    public void test1(){
        //                      参数      方法体
        Consumer<String> con1 = str -> System.out.println(str);
        con1.accept("北京");
        System.out.println("************************");
        PrintStream ps = System.out;
        Consumer<String> con2 = ps::println;
        con2.accept("beijing");
    }

    @Test
    public void test2(){
        Employee employee = new Employee(1001,"Tom",29);
        Supplier<String> sup1 = ()-> employee.getName();
        System.out.println(sup1.get());
        System.out.println("*********************");
        Supplier<String> sup2 = employee::getName;
        System.out.println(sup2.get());
    }
    //情况二:类型::静态方法
    //Comparator中int compare(T t1,T t2)
    //Integer 中的int compare(T t1,T t2)
    @Test
    public void test3(){
        Comparator<Integer> com1 = (t1, t2) -> Integer.compare(t1,t2);
        System.out.println(com1.compare(12,21));
        System.out.println("**********************");
        //                   调用者或调用者类型  方法体
        Comparator<Integer> com2 = Integer::compare;
        System.out.println(com2.compare(112,21));
    }
    //Function中的R apply(T t)
    //Math中的Long round(Double d)
    @Test
    public void test4(){
        Function<Double,Long> func1 = new Function<Double, Long>() {
            @Override
            public Long apply(Double d) {
                return Math.round(d);   //这里的round是静态方法,Math是类
            }
        };
        System.out.println(func1.apply(3.14));
        System.out.println("********************");
        Function<Double,Long> fun2 = d -> Math.round(d);
        System.out.println(fun2.apply(4.34));
        System.out.println("*********************");
        Function<Double,Long> fun3 = Math::round;
        System.out.println(fun3.apply(4.44));
    }
    //情况三:类::实例方法
    //Comparator中的int comapre(T t1,T t2)
    //String中的int t1.compareTo(t2)
    @Test
    public void test5(){
        Comparator<String> com1 = (s1,s2)-> s1.compareTo(s2);
        System.out.println(com1.compare("abc","abd"));

        System.out.println("***********");
        Comparator<String> com2 = String:: compareTo;
        System.out.println(com2.compare("abd","abc"));
    }

    public void test6(){
        BiPredicate<String,String> pre1 = (s1, s2) -> s1.equals(s2);
        System.out.println(pre1.test("abc","abc"));
        System.out.println("****************************");
        BiPredicate<String,String> pre2 = String::equals;
        System.out.println(pre2.test("abc","abd"));
    }
    //Function中的R apply(T t)
    //Employee中的String getName();
    @Test
    public void test7(){
        Function<Employee,String> func1 =  e -> e.getName();
        System.out.println(func1.apply(new Employee(1002,"Jack",33)));
        System.out.println("*****************************");
        Function<Employee,String> func2 = Employee::getName;
        System.out.println(func2.apply(new Employee(1003,"Mack",23)));
    }

}

class Employee{
    int id;
    String name;
    int age;

    public Employee(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public Employee(){
        System.out.println("Employee空参构造器");
    }
    public Employee(Integer id){
        this.id = id;
    }
    public Employee(Integer id,String name){
        this.id = id;
        this.name = name;
    }
}
package lambda_;

/**
 * @author 小黄debug  on 2022/4/9
 * @version 1.0
 */
@FunctionalInterface    //可加可不加,加了做校验
public interface MyInterface {

    void method1();
}
package lambda_;

import org.junit.Test;

import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 一、构造器引用
 *      和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致
 *      抽象方法的返回值类型即为构造器所属的类的类型
 * 二、数组引用
 *      大家可以把数组看做是一个特殊的类,则写法与构造器引用一致。
 *
 * @author 小黄debug  on 2022/4/9
 * @version 1.0
 */
public class ConstructorRefTest {
    //构造器引用
    //Supplier中的T get()
    //Employee的空参构造器: Employee()
    @Test
    public void test1(){
        Supplier<Employee> sup = new Supplier<Employee>() {
            @Override
            public Employee get() {
                return new Employee();
            }
        };
        sup.get();
        System.out.println("*************************88");
        Supplier<Employee> sup1=()-> new Employee();
        sup1.get();
        System.out.println("**********************");
        Supplier<Employee> sup2 = Employee:: new;
        System.out.println(sup2.get());
    }
    //Function中的R apply(T t)
    @Test
    public void test2(){
        Function<Integer,Employee> func1 = id -> new Employee(id);
        Employee employee = func1.apply(1001);
        System.out.println(employee);
        System.out.println("********************");
        Function<Integer ,Employee> func2 = Employee:: new ;
        Employee apply = func2.apply(1002);
        System.out.println(apply);
    }
    //BiFunction中的R apply(T t,U u)
    @Test
    public void test3(){
        BiFunction<Integer,String,Employee> func1 = (id, name) -> new Employee(id,name);
        System.out.println(func1.apply(1001,"TOm"));
        System.out.println("********************");
        BiFunction<Integer,String,Employee> func2 = Employee::new;
        System.out.println(func2.apply(1002,"Tom"));
    }
    //数组引用
    //Function中的R apply(T t)
    @Test
    public void test4(){
        Function<Integer,String[] > func1 = length -> new String[length];
        String[] arr1 = func1.apply(5);
        System.out.println(Arrays.toString(arr1));
        System.out.println("*******************");
        Function<Integer,String[]> func2 = String[] :: new;
        String[] arr2 = func2.apply(10);
        System.out.println(Arrays.toString(arr2));
    }

}

16-4 强大的Stream API

Stream API说明

Java8中有两大最为重要的改变。第一个是Lambda表达式;另一个则是Stream API

Stream API(java.util.stream)把真正的函数式编程风格引入到Java中。这是目前为止对Java类库最好的补充,因为Stream API可以极大提供Java程序员的生产力,让程序 员写出高效率,干净、简洁的代码。

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

为什么要使用Stream API

实际开发中,项目中多数数据源来自睚Mysql,Oracle等,但现在数据源可以更多了,有MongDB,Radis等,而这些NoSQL的数据就老板娘Java层面去处理

Stream 和Collection 集合的区别:Collection是一种静态的内存数据结构,而Stream是有关计算的。前者是主要面向内存,存储在内存中后者主要是面向CPU,通过CPU实现计算

什么是Stream

Stream到底是什么呢?

是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列

”集合讲的是数据,Stream讲的是计算“

注意:

1、Stream自己不会存储元素。

2、Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream

3、Stream操作是延迟执行的。这意味着他们会等到需要结果 的时候才执行。

Stream的操作三个步骤

1、创建Stream

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

2、中间操作

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

3、终止操作(终端操作)

一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用。

创建Stream 方式一:通过集合

Java8中的Collection接口被扩展,提供了两个获取流的方法

default Stream<E> stream():返回一个顺序流

default Stream<E> parallelStream(): 返回一个并行流

创建Stream方式二:通过数据

Java8中的Arrays的静态方法stream()可以获取数组流

static <T> Stream<T> stream(T[] array):返回一个流

重载形式,能够处理对应基本类型的数组:
public static IntStream steam(int[] array)

public static LongStream steam(long[] array)

public static DoubleStream stream(double[] array)

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

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

public static<T> Stream<T> of(T... values):返回一个流

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

可以使用静态方式Stream。Stream.iterate()和Stream。enerate(),创建无限流

*迭代

public static<T> Stream<T> iterate(final T seed,final UnaryOperator<T> f)

*生成

public static<T> Stream<T> generate(Supplier<T> s)

package stream_;

import org.junit.Test;

import java.io.PrintStream;
import java.util.*;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 *
 * 1、Stream关注的是对数据的运算,与CPU打交道
 *      集合关注的是数据存储,与内存打交道
 *
 * 2、
 * 1)Stream 自己不会存储元素。
 * 2)Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
 * 3)Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行
 *
 * 3、 Stream 执行流程
 * 1) Stream 的实例化
 * 2) 一系列的中间操作(过滤、映射、。。。)
 * 3) 终止操作
 *
 * 4、说明
 * 4.1一个中间操作链,对数据源的数据进行处理
 * 4.2一旦执行终止操作,就执行蹭操作链,并生产结果 ,之后,不会再被使用
 *
 * @author 小黄debug  on 2022/4/10
 * @version 1.0
 */
public class StreamAPITest {
    //创建Stream 方式一:通过集合
    @Test
    public void test1(){
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1001,"jack1",23));
        employees.add(new Employee(1002,"jack2",23));
        employees.add(new Employee(1003,"jack3",23));
        employees.add(new Employee(1004,"jack4",23));
        employees.add(new Employee(1005,"jack5",23));
        employees.add(new Employee(1006,"jack6",23));

        //defalt Stream<E> stream(): 返回一个顺序流
        Stream<Employee> stream = employees.stream();
        //default Stream<E> parallelStrem(): 返回一个并行流
        Stream<Employee> parallelStream = employees.parallelStream();
    }


    //创建Stream方式二:通过数组
    @Test
    public void test2(){
        int[] arr = new int[]{1,2,3,4,5};
        //调用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);
    }
    //创建Stream方式三:通过Stream的of()
    @Test
    public void test3(){
        Stream.of(1,2,3,4,5);
    }

    //创建Stream方式四:创建无限流
    @Test
    public void test4(){
        //迭代
        //public static 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);
    }


}

class Employee{
    int id;
    String name;
    int age;
    double salary;

    public double getSalary() {
        return salary;
    }

    public Employee(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public Employee(int id, String name, int age, double salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }
    public Employee(){
        System.out.println("Employee空参构造器");
    }
    public Employee(Integer id){
        this.id = id;
    }
    public Employee(Integer id,String name){
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id && age == employee.age && Double.compare(employee.salary, salary) == 0 && Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, age, salary);
    }
}

Stream的中间操作

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

1、筛选与切片

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

2、映射

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

3、排序

方法描述
sorted()产生一个新流,其中按自然顺序排序
sorted(Comparator con)产生一个新流,其中按比较器顺序排序
package stream_;

import org.junit.Test;

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

/**
 * @author 小黄debug  on 2022/4/10
 * @version 1.0
 */
public class StreamAPITest1 {
    //1、筛选与切片
    @Test
    public void test1(){
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1001,"jack1",23,4000));
        employees.add(new Employee(1002,"jack2",23,5000));
        employees.add(new Employee(1003,"jack3",23,4500));
        employees.add(new Employee(1004,"jack4",23,6000));
        employees.add(new Employee(1005,"jack5",23,7000));
        employees.add(new Employee(1006,"jack6",23,10000));

        //filter(Predicate p)----接收Lambda,从流中排除某些元素,过滤
        Stream<Employee> stream = employees.stream();
        stream.filter(e -> e.getName().equals("jack6")).forEach(System.out::println);
        System.out.println("******************************");
        //练习:查询员工表中薪资大于6000的员工信息
        stream = employees.stream();
        stream.filter(e -> e.getSalary() > 6000).forEach(System.out::println);

        //limit(n) ----截断流,使其元素不超过给定数量
        System.out.println();
        employees.stream().limit(3).forEach(System.out::println);
        System.out.println();

        //skiip(n) -----跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足N个,则返回一个空的流
        System.out.println();
        employees.stream().skip(3).forEach(System.out::println);
        //distinct() ----筛选,通过流所生成元素的hashCode()和equals()去除重复元素
        //注意此方法使用需要重写hashCode的方法和equals方法
        System.out.println();
        employees.add(new Employee(1010,"刘强东",40,8000));
        employees.add(new Employee(1010,"刘强东",40,8000));
        employees.add(new Employee(1010,"刘强东",40,8000));
        employees.add(new Employee(1010,"刘强东",40,8000));
        employees.add(new Employee(1010,"刘强东",40,8000));
        employees.stream().distinct().forEach(System.out::println);
    }
    //映射
    @Test
    public void test2(){
        //map(Function f)----接收一个函数作为参数,将元素转换成其它形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素
        List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
        list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);
        //练习1:获取员工姓名长度大于3的员工的姓名
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1101,"小李",23,5000));
        employees.add(new Employee(1101,"李连杰",23,5000));
        employees.add(new Employee(1101,"曹德旺",23,5000));
        employees.add(new Employee(1101,"刘德华",23,5000));
        employees.add(new Employee(1101,"张灿",23,5000));

        System.out.println("********************");
        Stream<String> nameStream = employees.stream().map(Employee::getName);
        nameStream.filter(name -> name.length() >= 3).forEach(System.out::println);
        System.out.println();
        employees.stream().filter(employee -> employee.getName().length()>= 3).forEach(System.out::println);
        //练习2 :
        System.out.println("------------------------------");
        Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest1::fromStringToStream);
        streamStream.forEach(s -> {
            s.forEach(System.out::println);
        });
        System.out.println("-------------------------------");
        Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream);
        characterStream.forEach(System.out::println);
    }
    @Test
    public void test3(){
        List list1 = new ArrayList();
        list1.add(1);
        list1.add(2);
        list1.add(3);

        ArrayList list2 = new ArrayList();
        list2.add(4);
        list2.add(5);
        list2.add(6);

        //list1.add(list2);
       // System.out.println(list1);
        list1.addAll(list2);
        System.out.println(list1);
    }
    //将字符串中的多个字符构成的集合转换为对应的Stream实例
    public static Stream<Character> fromStringToStream(String str){
        ArrayList<Character> list = new ArrayList<>();
        for(Character c: str.toCharArray()){
            list.add(c);
        }
        return list.stream();
    }
    //3-排序
    @Test
    public void test4(){
        //sorted()---自然排序
        List<Integer> list = Arrays.asList(12,34,43,56,0,-98,7);
        list.stream().sorted().forEach(System.out::println);
        //sorted(Comparator com)----定制排序
        //java.lang.ClassCastException: stream_.Employee cannot be cast to java.lang.Comparable
        //抛异常的原因,Employee没有实现Comparable接口
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1001,"zhangsan",33,12000));
        employees.add(new Employee(1002,"zhangsan",35,12000));
        employees.add(new Employee(1003,"zhangsan",34,12000));
        employees.add(new Employee(1004,"zhangsan",23,12000));
        employees.add(new Employee(1005,"zhangsan",93,12000));
        //employees.stream().sorted().forEach(System.out::println);
        //employees.stream().sorted((e1,e2)-> Integer.compare(e1.getAge() , e2.getAge())).forEach(System.out::println);
        employees.stream().sorted((e1,e2)-> {
            int compare = Integer.compare(e1.getAge(), e2.getAge());
            if(compare != 0){
                return compare;
            }else{
                return Double.compare(e1.getSalary(),e2.getSalary());
            }
        }).forEach(System.out::println);

    }
}











Stream的终止操作

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

1、匹配与查找

方法描述
allMatch(Predicate p)检查是否匹配所有元素
anyMatch(Predicate p)检查是否至少匹配一个元素
noneMatch(Predicate p)检查是否没有匹配所有元素
findFirst()返回第一个元素
findAny()返回当前流中的任意元素
方法描述
count返回流中元素的总个数
max(Comparator c)返回流中最大值
min(Comparator c)返回流中最小值
forEach(Consumer c)内部迭代

2、归约

方法描述
reduce(T iden,Binary Operator b)可以将流中元素反复结合起来,得到一个值。返回T
reduce(BinaryOperator b)

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

备注:map和reduce的连接通常称为map-reduce模式,因Google用它来进行网络搜索而出名

3、收集

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

Collection接口中方法的实现决定了如何对流执行收集的操作(如收集到List、Set、Map)。

另外,Collectors实用类提供了很多静态方法,可以方便地创建觉收集要器实例,具体方法与实例如下表

方法返回类型作用
toListList<T>

把流中元素收集到List

List<Employee>  emps = list.stream().collect(Collectors.toList());
toSetSet<T>把流中元素收集到Set
Set<Employee> emps = list.stream().collect(Collectors.toSet());
toCollectionCollection<T>把流中远征经收到创建的集合
Collection<Employee> emps = list.stream().collect(Collectors.toCollection(ArrayList::new));
countingLong计算流中元素的个数
long count = list.stream().collect(Collectors.counting());
summingIntInteger对流中元素的整数属性求和
int total = list.stream().collect(Collectors.summingInt(Employee::getSalary));
averagingIntDouble计算流中元素Integer属性的平均值
double agv = list.stream().collect(Collectors.averagingInt(Employee::getSalary));
summarizingIntIntSummaryStatistics收集流中Integer属性的统计值。如:平均值
int SummaryStatisticsiss = list.stream().collect(Collectors.summarizingInt(Employee::getSalary));

package stream_;

import org.junit.Test;

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

/**
 * 测试Stream的终止操作
 * @author 小黄debug  on 2022/4/10
 * @version 1.0
 */
public class StreamAPITest2 {
    @Test
    public void test1(){
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1001,"zhangsan",33,12000));
        employees.add(new Employee(1002,"zhangsan",35,12000));
        employees.add(new Employee(1003,"雷军",16,12000));
        employees.add(new Employee(1004,"zhangsan",23,12000));
        employees.add(new Employee(1005,"zhangsan",93,12000));
        //allMath(Predicate p)----检查是否匹配所有元素
        //练习:是否所有的员工的年龄都大于18
        boolean b = employees.stream().allMatch(e -> e.getAge() > 18);
        System.out.println(b);
        //anyMatch(Predicate p)-----检查是否至少匹配一个元素
        boolean lei = employees.stream().anyMatch(e -> e.getName().startsWith("雷"));
        System.out.println(lei);
        //noneMatch(Predicate p)----检查是否没有匹配的元素。
        boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));
        System.out.println(noneMatch);
        //findFirst----返回第一个元素
        Optional<Employee> first = employees.stream().findFirst();
        System.out.println(first);
        //findAny----返回当前流中的任意元素
        Optional<Employee> any = employees.parallelStream().findAny();
        System.out.println(any);
    }
    @Test
    public void test2(){
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1001,"zhangsan",33,4000));
        employees.add(new Employee(1002,"zhangsan",35,5000));
        employees.add(new Employee(1003,"雷军",16,12000));
        employees.add(new Employee(1004,"zhangsan",23,3500));
        employees.add(new Employee(1005,"zhangsan",93,11000));

        //count---返回流中元素的总个数
        long count = employees.stream().count();
        System.out.println("一共有"+count+"人");
        //练习,薪资大于5000的员工
        long count1 = employees.stream().filter(e -> e.getSalary() > 5000).count();
        System.out.println("薪资大于5000的员工有"+count1+"人");
        //max(Comparator c)返回流中最大值
        //练习:返回最高的工资
        Stream<Double> doubleStream = employees.stream().map(e -> e.getSalary());
        Optional<Double> maxSalary = doubleStream.max(Double::compare);
        System.out.println(maxSalary);
        //min(Comparator c)返回流中最小值
        //练习返回最低工资的员工
        Optional<Employee> minSalaryEmployee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(minSalaryEmployee);

        //forEach(Consumer c)内部迭代
        employees.stream().forEach(System.out::println);
    }

    //2-归约
    @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);
        //reduce(BinaryOperator) ---可以将流中元素反复结合起来,得到一个值,返回Option<T>
        //练习2: 计算公司所有员工工资的总和
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1001,"zhangsan",33,4000));
        employees.add(new Employee(1002,"zhangsan",35,5000));
        employees.add(new Employee(1003,"雷军",16,12000));
        employees.add(new Employee(1004,"zhangsan",23,3500));
        employees.add(new Employee(1005,"zhangsan",93,11000));
        Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
        //Optional<Double> sumMoney = salaryStream.reduce(Double::sum);
        Optional<Double> sumMoney = salaryStream.reduce((s1,s2)->{
            return s1+s2;
        });
        System.out.println(sumMoney);

    }
    //3-收集
    @Test
    public void test4(){
        //collect(Collector c)---将流转换为其他形式。接收一个Collector接口的实现,用于给Stream返回list集合
        //练习1:查找工资大于6000的员工,结果返回一个List或Set
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1001,"zhangsan",33,4000));
        employees.add(new Employee(1002,"zhangsan",35,5000));
        employees.add(new Employee(1003,"雷军",16,12000));
        employees.add(new Employee(1004,"zhangsan",23,3500));
        employees.add(new Employee(1005,"zhangsan",93,11000));
        List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());
        employeeList.forEach(System.out::println);
        System.out.println();
        Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
        employeeSet.forEach(System.out::println);
        System.out.println();
    }
}

16-5 Optional类

到目前为止,臭名昭著的空指针异常是导致Java应用程序失败的常见原因。以前,为了解决空指针异常,Google公司著名的Guava项目引入了Optional类,Guava通过检查空值的方式来防止代码污染,它鼓励程序员写更干净的代码。受到Google Guava的启发,Optional类已经成为Java8类库的一部分。

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

Optional类的Javadoc描述如下:这是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回对象

创建Optional类对象的方法

》Optional.of(T t):创建一个Optional实例,t必须为空;

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

》Optional.ofNullable(T t): t可以为null

判断Optional容器中是否包含对象

》booelan isPresent():判断是否包含对象

》void ifPresent(Consumer<? super T> consumer):

接口的实现代码,并且该值会作为参数传给它。

》T get():如果调用对象包含值,返回该值,否则抛异常

》T orElse(T other):如果有值则将其返回,否则返回指定的other对象

》T orElseGet(Supplier<? extends T> other):如果有值则将其返回,否则返回由Supplier接口实现提供的对象。

》T orElse THrow(Supplier<? extends X> exceptionSupplier):如果有值则将其返回,否则抛出由Supplier接口实现提供的异常。

package optional_;

/**
 * @author 小黄debug  on 2022/4/10
 * @version 1.0
 */
public class Boy {
    private Girl girl;

    public Boy(Girl girl) {
        this.girl = girl;
    }
    public Boy(){

    }

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

    public Girl getGirl() {
        return girl;
    }

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

/**
 * @author 小黄debug  on 2022/4/10
 * @version 1.0
 */
public class Girl {
    private String name;
    public Girl(){

    }

    public Girl(String name) {
        this.name = name;
    }

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

    public String getName() {
        return name;
    }

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

import org.junit.Test;

import java.util.Optional;

/**
 * @author 小黄debug  on 2022/4/10
 * @version 1.0
 */
public class OptionalTest {
    /*
    Optional.of(T t):创建一个Optional实例,t必须非空
    Optional.empty():创建一个空的Optional实例
    Optional.ofNullable(T t):t可以为null
     */

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

    public String getGirlName(Boy boy){
        return boy.getGirl().getName();
    }
    @Test
    public void test3(){
        Boy boy = new Boy();
        String girlName = getGirlName(boy);
        System.out.println(girlName);
    }
    //由于以上会出现空指针异常,以下为优化后的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);
    }
    //使用Opational类的getGirlName2
    public String getGirlName2(Boy boy){
        Optional<Boy> boyOptional = Optional.ofNullable(boy);
        Boy boy1 = boyOptional.orElse(new Boy(new Girl("迪丽热巴")));
        Girl girl = boy1.getGirl();
        Optional<Girl> girl1 = Optional.ofNullable(girl);
        Girl girl2 = girl1.orElse(new Girl("古力娜扎"));
        return girl2.getName();
    }
    @Test
    public void test5(){
    Boy boy = null;
        String girlName2 = getGirlName2(boy);
        System.out.println(girlName2);
        boy = new Boy();
        String girlName21 = getGirlName2(boy);
        System.out.println(girlName21);
        boy = new Boy(new Girl("苍老师"));
        String girlName22 = getGirlName2(boy);
        System.out.println(girlName22);

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值