当前位置:   article > 正文

JDK8的新特性_jdk8新特性

jdk8新特性

1JDK8的新特性

1. lambda表达式
2. 函数式接口。
3. 方法引用。
4. Stream流
5. 日期时间类

2 .lambda表达式

概念:

语法: 

注意: 函数式接口:接口中只有一个抽象方法。

(参数1,参数2): 抽象方法的参数

->: 分隔符

{}:表示抽象方法的实现

 例子:

  1. public class Test01 {
  2. public static void main(String[] args) {
  3. //该构造方法需要传递一个线程任务对象。Runnable类型
  4. My task=new My();
  5. Thread t1=new Thread(task);
  6. t1.start();
  7. //匿名内部类
  8. Runnable task02=new Runnable() {
  9. @Override
  10. public void run() {
  11. System.out.println("这时匿名内部类方式的任务对象");
  12. }
  13. };
  14. Thread t2=new Thread(task02);
  15. t2.start();
  16. }
  17. }
  18. class My implements Runnable{
  19. @Override
  20. public void run() {
  21. System.out.println("自定义任务接口类");
  22. }
  23. }

分析代码:

  • Thread 类需要 Runnable 接口作为参数,其中的抽象 run 方法是用来指定线程任务内容的核心

  • 为了指定 run 的方法体,不得不需要 Runnable 接口的实现类

  • 为了省去定义一个 Runnable 实现类的麻烦,不得不使用匿名内部类

  • 必须覆盖重写抽象 run 方法,所以方法名称、方法参数、方法返回值不得不再写一遍,且不能写错

  • 而实际上,似乎只有方法体才是关键所在

 这时可以使用lambda表示完成上面的要求。

  1. //lambda表达式
  2. Runnable task03 = ()-> {
  3. System.out.println("这是使用Lambda表达式完成的");
  4. };
  5. Thread t3=new Thread(task03);
  6. t3.start();

前提:必须是函数式接口。

简化匿名内部类的使用,语法更加简单。

2.1 无参无返回值

  1. public class Test02 {
  2. public static void main(String[] args) {
  3. //匿名内部类
  4. Swimmable swimmable=new Swimmable() {
  5. @Override
  6. public void swimming() {
  7. System.out.println("这时使用匿名内部类的方式");
  8. }
  9. };
  10. fun(swimmable);
  11. //lambda表达式
  12. // Swimmable swimmable1=()->{
  13. // System.out.println("使用lambda表达式");
  14. // };
  15. fun(()->{System.out.println("使用lambda表达式");});
  16. }
  17. public static void fun(Swimmable w){
  18. w.swimming();
  19. }
  20. }
  21. //函数式接口
  22. interface Swimmable{
  23. public void swimming();
  24. }

2.2 练习有参数有返回值的Lambda

下面举例演示 java.util.Comparator 接口的使用场景代码,其中的抽象方法定义为:

  • public abstract int compare(T o1, T o2);

当需要对一个对象集合进行排序时, Collections.sort 方法需要一个 Comparator 接口实例来指定排序的规则。

  1. public class Test03 {
  2.    public static void main(String[] args) {
  3.        List<Person> personList=new ArrayList<>();
  4.        personList.add(new Person("刘德华",50,175));
  5.        personList.add(new Person("张学友",55,178));
  6.        personList.add(new Person("杨紫琼",45,170));
  7.        personList.add(new Person("闫克起",18,185));
  8.        //对集合中的元素进行排序 按照年龄从大到小。
  9.        //传统做法:Comparator: 排序规则接口
  10. //Comparator<Person> comparator = new Comparator<Person>() {
  11. //           //int: 0表示新加的元素和集合中原来的比对的相同
  12. //                 //1: o2比o1小
  13. //                 //-1: o2比o1大
  14. //           @Override
  15. //           public int compare(Person o1, Person o2) {
  16. //               return o2.getAge()-o1.getAge();
  17. //           }
  18. //       };
  19. //       Collections.sort(personList,comparator);
  20. //       for (Person p:personList){
  21. //           System.out.println(p);
  22. //       }        
  23. System.out.println("===============================lambda===========================");        Comparator<Person> comparator1 = (Person o1, Person o2)->{    
  24.        return o1.getAge()-o2.getAge();
  25.       };
  26.        Collections.sort(personList,comparator1);
  27.        for (Person p : personList) {          
  28.  System.out.println(p);
  29.       }
  30.   }}
  31. class Person {
  32.    private String name;
  33.    private int age;
  34.    private int height;
  35.    @Override
  36.    public String toString() {
  37.        return "Person{" +
  38. "name='" + name + '\'' +
  39.                ", age=" + age +
  40.                ", height=" + height +
  41.                '}';
  42.   }
  43.   public Person(String name, int age, int height) {
  44.        this.name = name;
  45.        this.age = age;
  46.        this.height = height;
  47.   }
  48.    public String getName() {
  49.        return name;
  50.   }
  51.    public void setName(String name) {
  52.        this.name = name;
  53.   }
  54.    public int getAge() {
  55.        return age;
  56.   }
  57.    public void setAge(int age) {
  58.        this.age = age;
  59.   }
  60.    public int getHeight() {
  61.        return height;  
  62. }    public void setHeight(int height) {
  63.        this.height = height;  
  64. }}

2.3 详细介绍lambda表达式

3. 函数式接口

 内置函数式接口的由来

  1. public class Test03 {
  2. public static void main(String[] args) {
  3. Operater o=arr -> {
  4. int sum=0;
  5. for(int n:arr){
  6. sum+=n;
  7. }
  8. System.out.println("数组的和为:"+sum);
  9. };
  10. fun(o);
  11. }
  12. public static void fun(Operater operater){
  13. int[] arr={2,3,4,5,6,7,11};
  14. operater.getSum(arr);
  15. }
  16. }
  17. @FunctionalInterface
  18. interface Operater{
  19. //求数组的和
  20. public abstract void getSum(int[] arr);
  21. }

分析

我们知道使用Lambda表达式的前提是需要有函数式接口。而Lambda使用时不关心接口名,抽象方法名,只关心抽 象方法的参数列表和返回值类型。因此为了让我们使用Lambda方便,JDK提供了大量常用的函数式接口。

常见得函数式接口

 java.util.function保存

 

 3.1Consumer<T>

有参数,无返回值。

  1. public class Test {
  2. public static void main(String[] args) {
  3. Consumer<Double> c= t->{
  4. System.out.println("洗脚花费了:"+t);
  5. };
  6. fun01(c,200);
  7. }
  8. //调用某个方法时,该方法需要的参数为接口类型,这时就应该能想到使用lambda
  9. public static void fun01(Consumer<Double> consumer,double money){
  10. consumer.accept(money);
  11. }
  12. }

3.2 Supplier<T>供给型函数式接口

T:表示返回结果的泛型

无参,想有返回结果的函数式接口时

T get();
  1. public class Test02 {
  2. public static void main(String[] args) {
  3. //Supplier<Integer> supplier=()->new Random().nextInt(10);
  4. fun(()->new Random().nextInt(10));
  5. }
  6. public static void fun(Supplier<Integer> supplier){
  7. Integer result = supplier.get();
  8. System.out.println("内容为:"+result);
  9. }
  10. }

3.3 Function<T,R> 函数型函数式接口

T: 参数类型的泛型

R: 函数返回结果的泛型

有参,有返回 值时。

例子: 传入一个字符串把小写转换为大写。

  1. public class Test03 {
  2. public static void main(String[] args) {
  3. fun((t)->{
  4. return t.toUpperCase();
  5. },"hello world");
  6. }
  7. //传入一个字符串,返回字符串的长度。
  8. public static void fun(Function<String,String> function,String msg){
  9. String s = function.apply(msg);
  10. System.out.println("结果为:"+s);
  11. }
  12. }

3.4 Predicated<T>

T: 参数的泛型

boolean test(T t);

 当传入一个参数时,需要对该参数进行判断时,则需要这种函数。

  1. public class Test04 {
  2. public static void main(String[] args) {
  3. fun(n->{
  4. return n.length()>3?true:false;
  5. },"栗毅");
  6. }
  7. public static void fun(Predicate<String> predicate,String name ){
  8. boolean b = predicate.test(name);
  9. System.out.println("该名称的长度是否长啊:"+b);
  10. }
  11. }

4. 方法引用。

4.1 lambda表达式的冗余

  1. package demo05;
  2. import java.util.function.Consumer;
  3. /**
  4. * @program: qy151-jdk8
  5. * @description:
  6. * @author: 闫克起2
  7. * @create: 2022-07-19 16:56
  8. **/
  9. public class Test01 {
  10. public static void main(String[] args) {
  11. Consumer<Integer[]> c=arr->{
  12. int sum=0;
  13. for(int b:arr){
  14. sum+=b;
  15. }
  16. System.out.println("数组的和为:"+sum);
  17. };
  18. fun(c);
  19. }
  20. public static void fun(Consumer<Integer[]> consumer){
  21. Integer[] arr={1,2,3,4,5};
  22. consumer.accept(arr);
  23. }
  24. public static void sum(Integer[] arr){
  25. int sum=0;
  26. for (int a:arr){
  27. sum+=a;
  28. }
  29. System.out.println("数组的和为:"+sum);
  30. }
  31. }

分析:

如果我们在Lambda中所指定的功能,已经有其他方法存在相同方案,那是否还有必要再写重复逻辑?可以直接“引 用”过去就好了:---方法引用。

  1. package demo05;
  2. import java.util.function.Consumer;
  3. /**
  4. * @program: qy151-jdk8
  5. * @description:
  6. * @author: 闫克起2
  7. * @create: 2022-07-19 16:56
  8. **/
  9. public class Test01 {
  10. public static void main(String[] args) {
  11. Consumer<Integer[]> c=Test01::sum;
  12. fun(c);
  13. }
  14. public static void fun(Consumer<Integer[]> consumer){
  15. Integer[] arr={1,2,3,4,5};
  16. consumer.accept(arr);
  17. }
  18. public static void sum(Integer[] arr){
  19. int sum=0;
  20. for (int a:arr){
  21. sum+=a;
  22. }
  23. System.out.println("数组的和为:"+sum);
  24. }
  25. }

请注意其中的双冒号 :: 写法,这被称为“方法引用”,是一种新的语法。

4.2 什么是方法引用

 方法引用的分类

4.3 实例方法引用

实例方法引用,顾名思义就是调用已经存在的实例的方法,与静态方法引用不同的是类要先实例化,静态方法引用类无需实例化,直接用类名去调用。

  1. public class Test03 {
  2. public static void main(String[] args) {
  3. //[3]对象方法引用: 类名::实例方法. (参数1,参数2)->参数1.实例方法(参数2)
  4. // Function<String,Integer> function=(str)->{
  5. // return str.length();
  6. // };
  7. // Function<String,Integer> function=String::length;
  8. //
  9. // Integer len = function.apply("hello");
  10. // System.out.println(len);
  11. //比较两个字符串的内容是否一致.T, U, R
  12. // R apply(T t, U u);
  13. // BiFunction<String,String,Boolean> bi=(t,u)->{
  14. // return t.equals(u);
  15. // };
  16. // BiFunction<String,String,Boolean> bi=String::equals;
  17. // Boolean aBoolean = bi.apply("hello", "world");
  18. // System.out.println(aBoolean);
  19. // [4]构造方法引用: 类名::new (参数)->new 类名(参数)
  20. // Supplier<String> supplier=()->{
  21. // return new String("hello");
  22. // };
  23. // Supplier<People> supplier=People::new;
  24. // Function<String,People> function=(n)->new People(n);
  25. Function<String,People> function= People::new;
  26. People s = function.apply("张三");
  27. System.out.println(s);
  28. }
  29. }
  30. class People{
  31. private String name;
  32. public People() {
  33. }
  34. public People(String name) {
  35. this.name = name;
  36. }
  37. @Override
  38. public String toString() {
  39. return "People{" +
  40. "name='" + name + '\'' +
  41. '}';
  42. }
  43. }

5.Stream流

Java8的两个重大改变,一个是Lambda表达式,另一个就是本节要讲的Stream API表达式。==Stream 是Java8中处理集合的关键抽象概念==,它可以对集合进行非常复杂的查找、过滤、筛选等操作.

5.1 为什么使用Stream流

当我们需要对集合中的元素进行操作的时候,除了必需的添加、删除、获取外,最典型的就是集合遍历。我们来体验 集合操作数据的弊端,需求如下:

一个ArrayList集合中存储有以下数据:张无忌,周芷若,赵敏,张强,张三丰,何线程
需求:1.拿到所有姓张的 2.拿到名字长度为3个字的 3.打印这些数据

代码如下:

  1. public class My {
  2. public static void main(String[] args) {
  3. // 一个ArrayList集合中存储有以下数据:张无忌,周芷若,赵敏,张强,张三丰
  4. // 需求:1.拿到所有姓张的 2.拿到名字长度为3个字的 3.打印这些数据
  5. ArrayList<String> list = new ArrayList<>();
  6. Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张强", "张三丰");
  7. // 1.拿到所有姓张的
  8. ArrayList<String> zhangList = new ArrayList<>(); // {"张无忌", "张强", "张三丰"}
  9. for (String name : list) {
  10. if (name.startsWith("张")) {
  11. zhangList.add(name);
  12. }
  13. }
  14. // 2.拿到名字长度为3个字的
  15. ArrayList<String> threeList = new ArrayList<>(); // {"张无忌", "张三丰"}
  16. for (String name : zhangList) {
  17. if (name.length() == 3) {
  18. threeList.add(name);
  19. }
  20. }
  21. // 3.打印这些数据
  22. for (String name : threeList) {
  23. System.out.println(name);
  24. }
  25. }
  26. }

分析:

这段代码中含有三个循环,每一个作用不同:

  1. 首先筛选所有姓张的人;

  2. 然后筛选名字有三个字的人;

  3. 最后进行对结果进行打印输出。

每当我们需要对集合中的元素进行操作的时候,总是需要进行循环、循环、再循环。这是理所当然的么?不是。循环 是做事情的方式,而不是目的。每个需求都要循环一次,还要搞一个新集合来装数据,如果希望再次遍历,只能再使 用另一个循环从头开始。

那Stream能给我们带来怎样更加优雅的写法呢?

Stream的更优写法

  1. public class Test {
  2. public static void main(String[] args) {
  3. ArrayList<String> list = new ArrayList<>();
  4. Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张强", "张三丰","何线程");
  5. list.stream()
  6. .filter(item->item.startsWith("张"))
  7. .filter(item->item.length()==3)
  8. .forEach(item-> System.out.println(item));
  9. }
  10. }

对集合的操作语法简洁:性能比传统快。

5.2 Stream流的原理

注意:Stream和IO流(InputStream/OutputStream)没有任何关系,请暂时忘记对传统IO流的固有印象!

Stream流式思想类似于工厂车间的“生产流水线”,Stream流不是一种==数据结构==,==不保存数据==,而是对数据进行==加工 处理==。Stream可以看作是流水线上的一个工序。在流水线上,通过多个工序让一个原材料加工成一个商品。

 Stream不存在数据,只对数据进行加工处理。

5.3 如何获取Stream流对象。

  

  1. public class Test02 {
  2. public static void main(String[] args) {
  3. //通过集合对象调用stream()获取流
  4. List<String> list=new ArrayList<>();
  5. list.add("闫克起");
  6. list.add("何线程");
  7. list.add("杨坤");
  8. list.add("王地");
  9. Stream<String> stream = list.stream();
  10. //通过Arrays数组工具类获取Stream对象
  11. int[] arr={3,4,5,63,2,34};
  12. IntStream stream1 = Arrays.stream(arr);
  13. //使用Stream类中of方法
  14. Stream<String> stream2 = Stream.of("hello", "world", "spring", "java");
  15. //LongStream
  16. LongStream range = LongStream.range(1, 10);
  17. //上面都是获取的串行流。还可以获取并行流。如果流中的数据量足够大,并行流可以加快处速度。
  18. Stream<String> stringStream = list.parallelStream();
  19. //
  20. // stringStream.forEach(item-> System.out.println(item));
  21. stringStream.forEach(System.out::println);
  22. }
  23. }

5.4 Stream流中常见的api

中间操作api:  一个操作的中间链,对数据源的数据进行操作。而这种操作的返回类型还是一个Stream对象。

终止操作api: 一个终止操作,执行中间操作链,并产生结果,返回类型不在是Stream流对象。

 

 (1)filter / foreach / count

  1. static List<Person> personList = new ArrayList<Person>();
  2. private static void initPerson() {
  3. personList.add(new Person("张三", 8, 3000));
  4. personList.add(new Person("李四", 18, 5000));
  5. personList.add(new Person("王五", 28, 7000));
  6. personList.add(new Person("孙六", 38, 9000));
  7. }
  8. class Person {
  9. private String name;
  10. private Integer age;
  11. private String country;
  12. private char sex;
  13. public Person(String name, Integer age, String country, char sex) {
  14. this.name = name;
  15. this.age = age;
  16. this.country = country;
  17. this.sex = sex;
  18. }
  19. }
  20. List<Person> personList = new ArrayList<>();
  21. personList.add(new Person("欧阳雪",18,"中国",'F'));
  22. personList.add(new Person("Tom",24,"美国",'M'));
  23. personList.add(new Person("Harley",22,"英国",'F'));
  24. personList.add(new Person("向天笑",20,"中国",'M'));
  25. personList.add(new Person("李康",22,"中国",'M'));
  26. personList.add(new Person("小梅",20,"中国",'F'));
  27. personList.add(new Person("何雪",21,"中国",'F'));
  28. personList.add(new Person("李康",22,"中国",'M'));

(2) map | sorted

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

  1. //对流中元素排序
  2. personList.stream()
  3. .sorted((o1,o2)->o1.getAge()-o2.getAge())
  4. .forEach(System.out::println);
  5. //集合中每个元素只要名.map--->原来流中每个元素转换为另一种格式。
  6. // personList.stream()
  7. // .map(item->{
  8. // Map<String,Object> m=new HashMap<>();
  9. // m.put("name",item.getName());
  10. // m.put("age",item.getAge());
  11. // return m;
  12. // })
  13. // .forEach(System.out::println);

(3) min max

获取员工中年龄最大的人

  1.       //查找最大年龄的人. max终止操作
  2.       Optional<Person> max = personList.stream()
  3. .max((o1, o2) -> o1.getAge() - o2.getAge());
  4.       System.out.println(max.get());

获取员工中年龄最小的人-- 省略  

(4)规约reduce

  1. //求集合中所有人的年龄和。
  2. Optional<Integer> reduce = personList.stream()
  3. .map(item -> item.getAge())
  4. .reduce((a, b) -> a + b);
  5. System.out.println(reduce.get());
  6. Integer reduce = personList.stream()
  7. .map(item -> item.getAge())
  8. .reduce(10, (a, b) -> a + b);
  9. System.out.println(reduce);

 (5)collect搜集 match find

  1. //findFirst match
  2. // Optional<Person> first = personList.parallelStream().filter(item -> item.getSex() == 'F').findAny();
  3. boolean b = personList.parallelStream().filter(item -> item.getSex() == 'F').noneMatch(item -> item.getAge() >= 20);
  4. System.out.println(b);
  5. //搜集方法 collect 它属于终止方法
  6. //年龄大于20且性别为M
  7. // List<Person> collect = personList.stream()
  8. // .filter(item -> item.getAge() > 20)
  9. // .filter(item -> item.getSex() == 'M')
  10. // .collect(Collectors.toList());
  11. //
  12. // System.out.println(collect);

6. 新增了日期时间类

旧的日期时间的缺点:

  1. 设计比较乱: Date日期在java.util和java.sql也有,而且它的时间格式转换类在java.text包。

  2. 线程不安全。

 

新增加了哪些类?

LocalDate: 表示日期类。yyyy-MM-dd

LocalTime: 表示时间类。 HH:mm:ss

LocalDateTime: 表示日期时间类 yyyy-MM-dd t HH:mm:ss sss

DatetimeFormatter:日期时间格式转换类。

Instant: 时间戳类。

Duration: 用于计算两个日期类

  1. package demo10;
  2. import java.time.Duration;
  3. import java.time.LocalDate;
  4. import java.time.LocalDateTime;
  5. import java.time.LocalTime;
  6. import java.time.format.DateTimeFormatter;
  7. /**
  8. * @program: qy151-jdk8
  9. * @description:
  10. * @author: 闫克起2
  11. * @create: 2022-07-20 17:22
  12. **/
  13. public class Test {
  14. public static void main(String[] args) {
  15. LocalDate now = LocalDate.now(); //获取当前日期
  16. LocalDate date = LocalDate.of(2022, 8, 23);//指定日期
  17. LocalTime now1 = LocalTime.now();//当前时间
  18. LocalTime of = LocalTime.of(17, 30, 20, 600);
  19. LocalDateTime now2 = LocalDateTime.now();//获取当前日期时间
  20. LocalDateTime now3 = LocalDateTime.of(2022,6,20,17,45,20);
  21. Duration between = Duration.between(now2, now3);
  22. System.out.println(between.toHours());
  23. DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
  24. LocalDate parse = LocalDate.parse("1999-12-12", dateTimeFormatter);//把字符串转换为日期格式
  25. String format = parse.format(dateTimeFormatter);
  26. }
  27. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/53117
推荐阅读
相关标签
  

闽ICP备14008679号