java8新特性知识点笔记

参考视频:尚硅谷java8新特性

1.Lambda表达式

介绍

image-20231121160224576 image-20231121160313468

使用

image-20231121160407146 image-20231121160415199
    // 1.无参,无返回值
    Runnable r1 = new Runnable() { //匿名内部类
        @Override
        public void run() {
            System.out.println("我爱njupt");
        }
    };
    Runnable runnable = () -> System.out.println("你好");

    // 2.只需一个参数,但没有返回值
    Consumer<String> consumer1 = new Consumer<String>() {
        @Override
        public void accept(String s) {
            System.out.println(s);
        }
    };
    consumer1.accept("666");
    Consumer<String> consumer2 = (str) -> { //参数str的String类型可以省略不写
        System.out.println(str);
    };
    consumer2.accept("666");

image-20231121161455237

类似的类型推断有:

ArrayList<Integer> arrayList = new ArrayList<>(); //后面<>可不写,因为类型推断

int[] arr = new int[]{1,2,3,4};
int[] arr = {1, 2, 3, 4}; //类型推断

2.函数式接口

介绍

image-20231121170029561 image-20231121170053252
// 自定义函数式接口
@FunctionalInterface
public interface myInterFace {
    void run(); // 只包含一个抽象方法
}

四大核心函数式接口

image-20231121170240592
    @Test
    public void test01() {
        List<String> list = Arrays.asList("北京", "天津", "南京", "味精");
        //1.不用lambda
        //        List<String> filterString = filterString(list, new Predicate<String>() {
        //            @Override
        //            public boolean test(String s) {
        //                return s.contains("京");
        //            }
        //        });
        //        System.out.println(filterString);

        //2.使用lambda
        List<String> filterString = filterString(list, s -> s.contains("京"));
        System.out.println(filterString);
    }


    public static 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;
    }

其他接口

image-20231121170307035

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

介绍

image-20231121215923505

使用

    // 情况一:对象 :: 实例方法
    //Consumer中的void accept(T t)
    //PrintStream中的void println(T t)
    @Test
    public void test1() {
        Consumer<String> con1 = str -> System.out.println(str);
        con1.accept("我爱njupt");
        System.out.println("******************************");

        PrintStream ps = System.out;
        Consumer<String> con2 = ps::println;
        con2.accept("我爱njupt");
    }

    //Supplier中的T get()
    //Employee中的String getName()
    @Test
    public void test2() {
        Person person = new Person(10, "ckz");
        Supplier<String> con = () -> person.getName();
        System.out.println(con.get());

        Supplier<String> con2 = person::getName;
        System.out.println(con2.get());
    }

    // 情况二:类 :: 静态方法
    //Comparator中的int compare(T t1,T t2)
    //Integer中的int compare(T t1,T t2)
    @Test
    public void test3() {
        Comparator<Integer> con = (x1, x2) -> Integer.compare(x1, x2);
        System.out.println(con.compare(12, 21));

        Comparator<Integer> con2 = Integer::compare;
        System.out.println(con2.compare(12, 21));
    }

    //Function中的R apply(T t)
    //Math中的Long round(Double d)
    @Test
    public void test4() {
        Function<Double, Long> func = d ->  Math.round(d);
        System.out.println(func.apply(4.5));

        Function<Double, Long> func2 = Math::round;
        System.out.println(func2.apply(4.5));
    }

    // 情况三:类 :: 实例方法  (有难度)
    // 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("ffc", "ffa"));
        Comparator<String> com2 = String::compareTo;
        System.out.println(com2.compare("ffc", "ffa"));
    }

    //BiPredicate中的boolean test(T t1, T t2);
    //String中的boolean t1.equals(t2)
    @Test
    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"));
    } 

注意

针对情况1和情况2:使用方法引用时,要求接口中的抽象方法的形参列表和返回值类型 与 方法引用的方法的形参列表和返回类型相同。

针对情况3:当函数式接口方法的第一个参数是需要引用方法的调用者,并且第二个参数是需要引用方法的参数(或无参数)时:ClassName:methodName

image-20231121221956676 image-20231121223340296
    //构造器引用
    //Supplier中的T get()
    //Employee的空参构造器:Employee()
    @Test
    public void test1() {
        Supplier<Person> sup1 = () -> new Person();
        System.out.println(sup1.get());

        Supplier<Person> sup2 = Person::new;
        System.out.println(sup2.get());
    }

    //BiFunction中的R apply(T t,U u)
    @Test
    public void test2() {
        BiFunction<String, Integer, Person> bif1 = (age, name) -> new Person(age, name);
        System.out.println(bif1.apply("czk", 11));

        BiFunction<String, Integer, Person> bif2 = Person::new;
        System.out.println(bif2.apply("czk", 11));
    }

    //数组引用
    //Function中的R apply(T t)
    @Test
    public void test3() {
        Function<Integer, String[]> func1 = length -> new String[length];
        String[] arr1 = func1.apply(5);
        System.out.println(arr1);

        Function<Integer, String[]> func2 = String[]::new;
        String[] arr2 = func1.apply(5);
        System.out.println(arr2);
    }

4.强大的StreamAPI

介绍

image-20231122123831144 image-20231122123849131 image-20231122123859135 image-20231122123906387

创建Stream的几种方式

//创建 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();
    }

    //创建 Stream方式二:通过数组
    @Test
    public void test2() {
        int[] arr = {1, 2, 3, 4, 5, 6};
        //调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流
        IntStream stream = 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)
        //遍历前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);

    }

Stream的中间操作

image-20231122170722812
//筛选与切片
@Test
public void test1() {
    List<Employee> employees = EmployeeData.getEmployees();
    Stream<Employee> stream = employees.stream();

    //filter(Predicate p)——接收 Lambda , 从流中排除某些元素。
    // forEach(Consumer<? super T> action)
    stream.filter(e -> e.getSalary() > 5000).forEach(System.out::println);

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

    System.out.println();
    //skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
    employees.stream().skip(3).forEach(System.out::println);

    System.out.println();
    employees.add(new Employee(1010, "czk", 23, 250000));
    employees.add(new Employee(1010, "czk", 23, 250000));
    employees.add(new Employee(1010, "czk", 23, 250000));
    employees.add(new Employee(1010, "czk", 23, 250000));
    employees.add(new Employee(1010, "czk", 23, 250000));
    //distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
    employees.stream().distinct().forEach(System.out::println);

}
image-20231122170735442 image-20231122170743411
//映射
@Test
public void test2() {
    //map(Function f)——接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。
    List<String> list = Arrays.asList("aa", "bb", "cc");
    list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);

    //练习1:获取员工姓名长度大于3的员工的姓名。
    List<Employee> employees = EmployeeData.getEmployees();
    Stream<String> nameStream = employees.stream().map(Employee::getName);
    nameStream.filter(str -> str.length() > 3).forEach(System.out::println);
}

//排序
@Test
public void test3() {
    List<Integer> arrayList = Arrays.asList(12, 31, 21);
    arrayList.stream().sorted().forEach(System.out::println);

    System.out.println();
    //自定义排序
    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);
}

终止操作

image-20231122174430258 image-20231122174440041
//匹配和查找
@Test
public void test1() {
    List<Employee> employees = EmployeeData.getEmployees();
    //allMatch(Predicate p)——检查是否匹配所有元素。
    boolean b = employees.stream().limit(3).allMatch(e -> e.getSalary() > 3000);
    System.out.println(b);

    //findFirst——返回第一个元素 返回类型为Optional类型
    Optional<Employee> first = employees.stream().findFirst();
    System.out.println(first);

    long count = employees.stream().count();
    System.out.println(count);

    //max(Comparator c)——返回流中最大值 类型为Optional
    Optional<Employee> employee1 = employees.stream().max((e1, e2) -> {
        return Double.compare(e1.getSalary(), e2.getSalary());
    });
    System.out.println(employee1);
}
image-20231122174450736
@Test
public void test2() {
    //reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T
    //BinaryOperator<T,T,T>
    List<Integer> list = Arrays.asList(1, 2, 5, 3);
    Integer sum = list.stream().reduce(0, Integer::sum);
    System.out.println(sum);

    //练习2:计算公司所有员工工资的总和
    List<Employee> employees = EmployeeData.getEmployees();
    Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);
    Optional<Double> sumMoney = salaryStream.reduce(Double::sum);
    System.out.println(sumMoney.get());
}
image-20231122192634611 image-20231122192648636

主要使用的是toList和toSet

// collect(Collector c)——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
// Collector 由Collectors调方法生成
// 练习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);

System.out.println();
Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
employeeSet.forEach(System.out::println);

5.Optional类

image-20231122195314678 image-20231122195324631
/*
    Optional.of(T t) : 创建一个 Optional 实例,t必须非空;
    Optional.empty() : 创建一个空的 Optional 实例
    Optional.ofNullable(T t):t可以为null
     */
    public String getInnerName(Outer outer) {
       //可能会报空指针异常 outer为空 或者 getInner()为空
       //System.out.println(outer.getInner().getName());
        Optional<Outer> outerOptional = Optional.ofNullable(outer);
        Outer outer1 = outerOptional.orElse(new Outer(new Inner("tom")));
        return outer1.getInner().getName();
    }

    @Test
    public void test1() {
        //Outer outer = null;
        //Outer outer = new Outer();
        //   getInnerName(outer);
        Outer outer = null;
        String name = getInnerName(outer);
        System.out.println(name);
    }
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值