Java入门 - 11 Java8新特性

Java8新特性

前言

本文为B站Java教学视频BV1Kb411W75N的相关笔记,主要用于个人记录与分享,如有错误欢迎留言指出。
本章笔记涵盖视频内容P666~P686

1. Lambda表达式

  • 定义:Lambda是一个匿名函数,可以把Lambda表达式理解为是一段可以传递的代码。使用它可以写出更简洁,更灵活的代码

  • Lambda表达式的使用

    1. 举例:(o1,o2) -> Integer.compare(o1,o2);

    2. 格式:

      ->:Lambda操作符 或 箭头操作符

      ->左侧:Lambda形参列表(接口中的抽象方法的形参列表)

      ->右侧:Lambda体(重写的抽象方法的方法体)

    3. Lambda表达式的使用:

      ->左边:lambda形参列表的参数类型可以省略(类型推断);如果lambda形参列表只有一个参数,则一对()也可省略

      ->右边:lambda体应该使用一对{}包裹;如果lambda体只有一条执行语句(可能是return语句),可以省略{}和return关键字

    4. Lambda表达式的本质:作为函数式接口的实例

    public class LamdaTest{
    
        //语法格式一:无参,无返回值
        @Test
        public void test1(){
            //原写法
            Runnable r1 = new Runnable(){
                public void run(){
                    System.out.println("输出语句1");
                }
            };
            r1.run();
    
            //Lambda表达式写法
            Runnable r2 = () -> System.out.println("输出语句2");
            r2.run();
        }
    
        //语法格式二:Lambda需要一个参数,但是没有返回值
        @Test
        public void test2(){
            //原写法
            Consumer<String> con = new Consumer<String>(){
                public void accept(String s){
                    System.out.println(s);
                }
            };
            con.accept("输出语句3");
    
            //Lambda表达式写法1
            Consumer<String> con1 = (String s) -> {
                System.out.println(s);
            };
            con1.accept("输出语句4");
    
            //语法格式三:数据类型可以忽略,因为可有编译器推断得出,称为"类型推断"
            //Lambda表达式写法2
            Consumer<String> con2 = (s) -> {
                System.out.println(s);
            };
            con2.accept("输出语句5");
        	/*
    		类似的类型推断,在其它的语法中也出现过
    		ArrayList<String> list = new ArrayList<>();	//第二个<>内无需添加类型
    		int[] arr = {1,2,3}; //不需要写new和后续的类型
    		*/
    
            //语法格式四:lambda若只需要一个参数时,参数的小括号可以省略
            //Lambda表达式写法3
            Consumer<String> con3 = s -> {
                System.out.println(s);
            };
            con3.accept("输出语句6");
        }
    
        //语法格式五:Lambda需要两个或以上的参数,多条执行语句,并且可以有返回值
        @Test
        public void test3(){
    
            //原写法
            Comparator<Integer> com1 = new Comparator<Integer>(){
                public int compare(Integer o1,Integer o2){
                    System.out.println(o1);
                    System.out.println(o2);
                    return o1.compareTo(o2);
                }
            };
            System.out.println(com1.compare(12,21));
    
            //Lambda表达式写法
            Comparator<Integer> com2 = (o1,o2) -> {
                System.out.println(o1);
                System.out.println(o1);
                return o1.compareTo(o2);
            };
            System.out.println(com2.compare(12,5));
        }
    
        //语法格式六:当lambda体只有一条语句时,return和大括号都可以省略
        @Test
        public void test4(){
            //原写法
            Comparator<Integer> com2 = (o1,o2) -> {
                return o1.compareTo(o2);
            };
            System.out.println(com2.compare(12,5));
    
            //现写法
            Comparator<Integer> com3 = (o1,o2) -> o1.compareTo(o2);
            System.out.println(com3.compare(12,5));
        }
    }
    

2. 函数式接口

  • 定义:如果一个接口中,只声明了一个抽象方法,则此接口就称为函数式接口。可以在一个接口上使用@FunctionalInterface注解,这样可以检查它是否是一个函数式接口

  • Java内置四大核心函数式接口

函数式接口 参数类型 返回类型 用途
Consumer(消费型接口) T void 对类型为T的对象应用操作,包含方法void accept(T,t)
Supplier(供给型接口) T 返回类型为T的对象,包含方法T get()
Function<T,R> (函数型接口) T R 对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法R apply(T t)
Predicate(断定型接口) T boolean 确定类型为T的对象是否满足某约束,并返回boolean值。包含方法boolean test(T t)
  • 其它接口(仅作了解)
函数式接口 参数类型 返回类型 用途
BiFunction<T,U,R> T,U R 对类型为T,U参数应用操作,返回R类型的结果。包含方法 R apply(T t, U u)
UnaryOperator T T 对类型为T的对象进行一元运算,并返回T类型的结果。包含方法T apply(T t)
BinaryOperator T,T T 对类型为T的对象进行二元运算,并返回T类型的结果。包含方法T apply(T t1,T t2)
BiConsumer<T,U> T,U void 对类型为T,U参数应用操作。包含方法void accept(T t,U u)
BiPredicate<T,U> T,U boolean 包含方法为boolean test(T t,U u)

3. 引用

3.1 方法引用

  • 定义:当要传递给Lambda体的操作,已经有实现的方法了,就可以使用方法引用

  • 方法引用的使用

    • 要求:实现接口的抽象方法的参数列表和返回值类型,必须与方法引用的方法的参数列表和返回值类型保持一致
    • 格式:使用操作符"::"将类(或对象)与方法名分隔开来
    • 主要有如下三种使用情况:
      • 对象::实例方法名
      • 类::静态方法名
      • 类::实例方法名
  • 情况一:对象 :: 实例方法

public class MethodRefTest{

    //Consumer中的void accept(T t) 对应 PrintStream中的void println(T t)
    //两者返回值一致,参数个数一致,可以使用引用
    @Test
    public void test1(){
        //原Lambda表达式写法
        Consumer<String> con1 = str -> System.out.println(str);
        con1.accept("输出语句1");
        
        //引用写法
        PrintStream ps = System.out;
        Consumer<String> con2 = ps::println;
        con2.accept("输出语句2");
    }
    
    //Supplier中的T get() 对应 Employee中的String getName()
    //两者返回值一致,参数个数一致,可以使用引用
    @Test
    public void test2(){
        //原Lambda表达式写法
        Employee emp = new Employee(1001,"Tom",23,5600);
        Supplier<String> sup1 = () -> emp.getName();
        System.out.println(sup1.get());
        
        //引用写法
        Supplier<String> sup2 = emp::getName;
        System.out.println(sup2.get());
    }
}

class Employee{
    
    int ID;
    String name;
    int age;
    int salary;

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

    public String getName() {
        return name;
    }
}
  • 情况二:类::静态方法
public class MethodRefTest{
    //Comparator中的int compare(T t1,T t2) 对应 Integer中的int compare(T t1,T t2)
    //两者返回值一致,参数个数一致,可以使用引用
    @Test
    public void test3(){
        //原Lambda表达式写法
        Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2);
        System.out.println(com1.compare(12,21));
        
        //引用写法
        Comparator<Integer> com2 = Integer::compare;
        System.out.println(com2.compare(12,3));
    }
    
    //Function中的R apply(T t) 对应 Math中的Long round(Double d)
    //两者返回值一致,参数个数一致,可以使用引用
    @Test
    public void test4(){
        //原Lambda表达式写法
        Function<Double,Long> func1 = d -> Math.round(d);
        System.out.println(func1.apply(12.3));
        
        //引用写法
        Function<Double,Long> func2 = Math::round;
        System.out.println(func2.apply(12.6));
    }
}
  • 情况三:类::实例方法 (特别)
public class MethodRefTest{
    
    //Comparator中的int compare(T t1,T t2) 对应 String中的int t1.compareTo(t2)
    //此时t1作为调用者调用了t2,所以从某种角度上来说,它们符合使用引用的要求
    @Test
    public void test5(){
        //原Lambda表达式写法
        Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);
        System.out.println(com1.compare("abc","abd"));
        
        //引用写法
        Comparator<String> com2 = String::compareTo;
        System.out.println(com2.compare("abc","abm"));
    }
    
    //Function中的R apply(T t) 对应 Employee中的String getName()
    //此时t1作为调用者调用了空参的方法,所以从某种角度上来说,它符合使用引用的要求
    @Test
    public void test7(){
        Employee employee = new Employee(1001,"Jerry",23,6000);
        
        //原Lambda表达式写法
        Function<Employee,String> func1 = e -> e.getName();
        System.out.println(func1.apply(employee));
        
        //引用写法
        Function<Employee,String> func2 = Employee::getName;
        System.out.println(func2.apply(employee));
    }
}

class Employee{

    int ID;
    String name;
    int age;
    int salary;

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

    public String getName() {
        return name;
    }
}

3.2 构造器引用

  • 定义:和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。抽象方法的返回值类型即为构造器所属的类的类型
public class ConstructorRefTest{

    //构造器引用
    //Supplier中的T get()
    @Test
    public void test1(){

        //原Lambda表达式写法
        Supplier<Employee> sup1 = () -> new Employee();
        System.out.println(sup1.get());

        //引用写法
        Supplier<Employee> sup2 = Employee :: new;
        System.out.println(sup2.get());
    }

    //BiFunction中的R apply(T t,U u)
    @Test
    public void test2(){

        //原Lambda表达式写法
        BiFunction<Integer,String,Employee> func1 = (id, name)->new Employee(id,name);
        System.out.println(func1.apply(1001,"Tom"));

        //引用写法
        BiFunction<Integer,String,Employee> func2 = Employee :: new;
        System.out.println(func2.apply(1002,"Tom"));
    }

    //数组引用
    //Function中的R apply(T t)
    @Test
    public void test3(){

        //原Lambda表达式写法
        Function<Integer,String[]> func1 = length -> new String[length];
        String[] arr1 = func1.apply(5);
        System.out.println(Arrays.toString(arr1));

        //引用写法
        Function<Integer,String[]> func2 = String[] :: new;
        String[] arr2 = func2.apply(10);
        System.out.println(Arrays.toString(arr2));
    }
}

class Employee{

    int ID;
    String name;

    public Employee() {
    }

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

    public String getName() {
        return name;
    }
}

4. StreamAPI

  • Stream关注的是对数据的运算,与CPU交互

    集合关注的是数据的存储,与内存交互

  • Stream自己不会储存元素

    Stream不会改变源对象,它们会返回一个持有结果的新Stream

    Stream操作是延迟执行的,它们会等到需要结果时才执行

  • Stream执行流程

    1. Stream的实例化
    2. 一系列的中间操作(过滤,映射等)
    3. 终止操作
  • 注意事项:

    • 中间操作链会对数据源的数据进行处理
    • 一旦执行中止操作,就执行中间操作链,并产生结果。之后无法再被调用

4.1 Stream实例化

public class StreamAPITest{

    //创建Stream方式一:通过集合
    @Test
    public void test1(){
        //EmployeeData.getEmployees具体实现略
        List<Employee> employees = EmployeeData.getEmployees();

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

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

    //创建Stream方式二:通过数组
    @Test
    public void test2(){
        int[] arr = new int[]{1,2,3,4,5,6};

        //调用Arrays类的static <T> Stream<T> stream(T[] array):返回一个流
        IntStream stream1 = Arrays.stream(arr);
    }

    //创建Stream方式三:通过Stream的of()
    @Test
    public void test3(){
        Stream<Integer> stream = Stream.of(1,2,3,4,5);
    }

    //创建Stream方式四:创建无限流
    @Test
    public void test4(){
        //迭代
        //public static<T> Stream<T> iterate(final T seed,final UnaryOperator<T> f)
        //遍历前十个偶数
        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{

}

4.2 Stream的中间操作

  • 筛选与切片
public class StreamAPITest1{
    
    @Test
    public void test1(){
        //filter(Predicate p) —— 接收Lambda,从流中排除某些元素
        Stream<Employee> stream = list.stream();
        //查询员工表中薪资大于7000的员工信息
        stream.filter(e -> e.getSalary() > 7000).forEach(System.out::println);
        System.out.println();
        
        //limit(n) —— 截断流,使其元素不超过给定数量
        list.stream().limit(3).forEach(System.out::println);
        
        //skip(n) —— 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流
        list.stream().skip(3).forEach(System.out::println);
        
        //distinct() —— 筛选,通过流所生成元素的hashCode()和equals()去除重复元素
        list.stream().distinct().forEach(System.out::println);
    }
}
  • 映射
public class StreamAPITest1{

    @Test
    public void test2(){
        //map(Function f) —— 接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射一个新的元素
        List<String> list = Arrays.asList("a","b","c");
        list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);
    }
    
    @Test
    //flatMap(Function f) —— 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
    //将字符串中的多个字符构成的集合转换为对应的Stream的实例
    public Stream<Character> fromStringToStream(String str){
        ArrayList<Character> list1 = new ArrayList<>();
        for(Character c : str.toCharArray()){
            list1.add(c);
        }
        return list1.stream();
    }
}
  • 排序
public class StreamAPITest1{
    
    @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);
        
        //sorted(Comparator com) —— 定制排序
       	//略
    }
}

4.3 Stream的中止操作

  • 匹配和查找
public class StreamTest2{
    
    @Test
    public void test1(){
        //allMatch(Predicate p) —— 检查是否匹配所有元素
        //检测是否所有的员工年龄都大于18
        boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);
        System.out.println(allMatch);
        
        //anyMatch(Predicate p) —— 检查是否至少匹配一个元素
        //检测是否存在员工的工资大于10000
        boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000);
        System.out.println(anyMatch);
        
        //noneMatch(Predictae p) —— 检测是否没有匹配的元素
        //检测是否存在员工姓"雷"
 boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));
        System.out.println(employee);
        
        //findFirst —— 返回第一个元素
        Optional<Employee> employee = employees.stream().findFirst();
        System.out.println(employee);
        
        //findAny —— 返回当前流中的任意元素
        Optional<Employee> employee1 = employees.parallelStream().findAny();
        System.out.println(employee1);
        
        List<Employee> employees = EmployeeData getEmployees();
        //count —— 返回流中元素的总个数
        long count = employees.stream().filter(e -> e.getSalary() > 5000).count();
        System.out.println(count);
        
        //max(Comparator c) —— 返回流中最大值
        //返回最高的工资
        Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());
        Optional<Double> maxSalary = salaryStream.max(Double::compare);
        System.out.println(maxSalary);
        
        //min(Comparator c) —— 返回流中最小值
        //返回最低工资的员工
        Optional<Employee> employee = employees.stream().min((e1.e2) -> Double.compare(e1.getSalary(),e2.getSalary())
        System.out.println(employee);
        System.out.println();
        
        //forEach(Consumer c) —— 内部迭代
        employees.stream.forEach(System.out::println);
    }
}
  • 归约
public class StreamTest2{
    
    @Test
    public void test3(){
        //reduce(T identity, BinaryOperator) —— 可以将流中元素反复结合起来,得到一个值,返回T
        //计算1-10的自然数的和
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
        Integer sum = list.stream().reduce(0,Integer::sum);
        System.out.println(sum);
        
        //reduce(BinaryOperator) —— 可以将流中元素反复结合起来,得到一个值。返回Optional<T>
        //计算公司所有员工工资的总和
        List<Employee> employees = EmployeeData.getEmployees();
        Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
        Optional<Double> sumMoney = salaryStream.reduce(Double::sum);
        System.out.println(sumMoney);
    }
}
  • 收集
public class StreamTest2{
    
    @Test
    public void test4(){
        //collect(Collector c) —— 将流转换为其他形式。接收一个Collector接口的实现,用于给			  Stream元素做汇总的方法
        //查找工资大于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);
    }
}
/*
常见的Collectors内部方法有
toList: List<Employee> emps = list.stream().collect(Collectors.toList());
toSet: Set<Employee> emps = list.stream().collect(Collectors.toSet());
toCollection: Collection<Employee> emps = list.stream().collect(Collectors.toCollection(ArrayList::new));
*/

5. Optional类

  • 定义:Optional类是一个容器类,它可以保存类型T的值,代表这个值存在,或者仅仅保存null表示这个值不存在。原来用null表示一个值不存在,现在用Optional可以更好的表达,并且可以避免空指针异常

  • 创建Optional类对象的方法

    • Optional.of(T t):创建一个Optional实例,t必须非空
    • Optional.empty():船舰一个空的Optional实例
    • Optional.ofNullable(T t):t可以为null
  • 判断Optional容器中是否包含对象

    • boolean isPresent():判断是否包含对象
    • void ifPresent(Consumer<? super T> consumer):如果有值,就执行Consumer接口的实现代码,并且该值会作为参数传给它
  • 获取Optional容器的对象

    • T get():如果调用对象包含值,返回该值,否则抛异常
    • T orElse(T other):如果有值则将其返回,否则返回指定的other对象
    • T orElseGet(Supplier<? extends T> other):如果有值则将其返回,否则返回由Supplier接口实现提供的对象
    • T orElse Throw(Supplier<? extends X> exceptionSupplier):如果有值则将其返回,否则抛出由Supplier接口实现提供的异常
public class StreamTest3{
    
    @Test
    public void test1(){
        Girl girl = new Girl();
        girl = null;
        //of(T t):保证t是非空的
        Optional<Girl> optionalGirl = Optional.of(girl);
    }
    
    @Test
    public void test2(){
        Girl girl = new Girl();
        girl = null;
        //ofNullable(T t):t可以为null
        Optional<Girl> optionalGirl = Optional.ofNullable(girl);
        System.out.println(optionalGril);
    }
}
posted @   Solitary-Rhyme  阅读(162)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示