函数式编程(Lambda表达式、Optional、Stream流)

函数式编程(Lambda表达式、Optional、Stream流)


一、概述

1. 为什么要学习函数式编程?
  • 大数量下处理集合效率高
  • 代码可读性高
  • 消灭嵌套地狱

嵌套地狱:

	// 查询未成年作家的评分在70以上的书籍,由于洋流影响所以作家和书籍可能出现重复,需要进行去重
    List<Book> bookList = new ArrayList<>();
    Set<Book> uniqueBookValues = new Hashset<>();
    Set<Author> uniqueAuthorValues = new HashSet<>(0);
    for (Author author : authors) {
        if (uniqueAuthorValues.add(author)) {
            if (author.getAge() < 18) {
                List<Book> books = author.getBooks();
                for (Book book : books) {
                    if (book.getScore() > 70) {
                        if (uniqueAuthorValues.add(book)) {
                            bookList.add(book);
                        }
                    }
                }
            }
        }
    }
    System.out.println(bookList);

改为函数式编程:

    List<Book> collect = authors.stream(
            .distinct()
            .filter(author -> author.getAge() < 18)
            .map(author -> author.getBooks())
            .flatMap(CoTTection::stream)
            .filter(book -> book.getscore() > 70)
            .distinct()
            .co11ect(Collectors.toList();)
    system.out.println(collect);

2. 函数式编程思想

面向对象思想需要关注用什么对象完成什么事情。而函数式编程思想就类似于我们数学中的函数。它主要关注的是对数据进行了什么操作。

优点:

  • 代码简洁、快速开发;
  • 接近自然语言,易于理解;
  • 易于并发编程;

二、Lambda表达式

概述:

Lambda 是JDK8 中一个语法糖。他可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象。而是更关注我们对数据进行了什么操作。

基本格式:

(参数列表)->{代码}

例子:我们在创建线程并启动时可以使用匿名内部类的写法:

    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("任务代码");
        }
    }).start();

使用Lambda的格式对其进行修改后:

    new Thread( ()->{
        System.out.println("任务代码");
    }).start();

省略规则:

  • 参数类型可以省略;
  • 方法体内只有一句代码时大括号 return 和唯一一句代码的分号可以省略;
  • 方法只有一个参数时小括号可以省略;
  • 以上这些规则都记不住也可以省略不记;

三、Stream流

概述:

Java8 的 Stream 使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作。

案例准备:

@Data
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
public class Author {
    // id
    private Long id;
    // 姓名
    private String name;
    // 年龄
    private Integer age;
    // 简介
    private String intro;
    // 作品
    private List<Book> books;
}
@Data
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
public class Book {
    // id
    private Long id;
    // 书名
    private String name;
    // 分类
    private String category;
    // 评分
    private String score;
    // 简介
    private String intro;
}
public class TestStream {

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        System.out.println(authors + "\t");
    }

    private static List<Author> getAuthors() {
        Author author1 = new Author(1l, "蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
        Author author2 = new Author(2l, "呀拉索", 15, "疯狂也追逐不上他的思考速度", null);
        Author author3 = new Author(3l, "易", 14, "是这个世界在限制他的思维", null);
        Author author4 = new Author(4l, "易", 14, "是这个世界在限制他的思维", null);

        // 书籍列表
        List<Book> books1 = new ArrayList<>();
        List<Book> books2 = new ArrayList<>();
        List<Book> books3 = new ArrayList<>();

        books1.add(new Book(1l, "刀的两侧是光明与黑暗", "哲学,爱情", 88, "用一把刀划分了爱恨"));
        books1.add(new Book(2l, "一个人不能死在同一把刀下", "个人成长,爱情", 99, "讲述如何从失败"));

        books2.add(new Book(3l, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));
        books2.add(new Book(3l, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));
        books2.add(new Book(4l, "吹或不吹", "爱情,个人传记", 85, "一个哲学家的恋爱观注定很难把"));

        books3.add(new Book(5l, "你的剑就是我的剑", "爱情,个人传记", 85, "一个哲学家的恋爱观注定很难把"));
        books3.add(new Book(6l, "风与剑", "个人传记", 100, "两个哲学家"));
        books3.add(new Book(6l, "风与剑", "个人传记", 100, "两个哲学家"));

        author1.setBooks(books1);
        author2.setBooks(books2);
        author3.setBooks(books3);

        ArrayList<Author> authors = new ArrayList<>(Arrays.asList(author1, author2, author3));
        return authors;
    }
}

需求:

调用 getAuthors() 方法获取作家的集合,打印所有年龄小于18岁的作家的名字,并且要去重。

lambda 表达式初步改造:

public static void main(String[] args) {
    List<Author> authors = getAuthors();
    authors.stream()
            .distinct() // 去重
            .filter(new Predicate<Author>() {
                @Override
                public boolean test(Author author) {
                    return author.getAge() < 18;
                }
            }) // 条件过滤
            .forEach(new Consumer<Author>() {
                @Override
                public void accept(Author author) {
                    System.out.println(author.getName());
                }
            }); // 遍历打印
}

结果:
在这里插入图片描述

lambda 再次改造:

public static void main(String[] args) {
    List<Author> authors = getAuthors();
    authors.stream() // 把集合转换成流
            .distinct() // 去重
            .filter(author -> author.getAge() < 18) // 条件过滤
            .forEach(author -> System.out.println(author.getName())); // 遍历打印
}

可以通过打断点详细看到去重、过滤的过程:

在这里插入图片描述

四、Stream流常用操作

1. 创建流
  • 单列集合:集合对象.stream()
List<Author> authors = getAuthors();
authors.stream()
  • 数组:Arrays.stream(数组)或者直接使用 Stream.of 创建:
Integer[] arr = {1, 2, 3, 4, 5};
Stream<Integer> stream = Arrays.stream(arr);
Stream<Integer> stream2 = Stream.of(arr);
  • 双列集合:转换成单列集合后再创建
Map<String, Integer> map = new HashMap<>();
map.put("张三", 16);
map.put("李四", 19);
map.put("王五", 17);

Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();
stream.distinct()
        .filter(stringIntegerEntry -> stringIntegerEntry.getValue() > 16)
        .forEach(stringIntegerEntry -> System.out.println(stringIntegerEntry));

2. 方法介绍-中间操作
  • filter():过滤方法,对数据按条件进行过滤。
  • map():可以对流中的元素进行计算或转换,类似于做筛选,对原始数据做筛选。
List<Author> authors = getAuthors();
authors.stream()
        .map(author -> author.getName())
        .forEach(name -> System.out.println(name));

在这里插入图片描述

  • distinct():去除流中的重复元素。distinct 方法是依赖 Object 的 equals 方法来判断是否是相同对象的,所以需要注意重写equals 方法。
  • sorted():可以对流中的元素进行排序。

例:对流中的元素(Author)按照年龄进行降序排序,并且要求不能有重复的元素。

方法一:如果调用空参的 sorted() 方法,需要流中的元素实现 Comparable。

@Data
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
public class Author implements Comparable<Author> {
    // id
    private Long id;
    // 姓名
    private String name;
    // 年龄
    private Integer age;
    // 简介
    private String intro;
    // 作品
    private List<Book> books;

    @Override
    public int compareTo(Author o) {
//        return this.getAge() - o.getAge();  升序
        return o.getAge() - this.getAge();  // 降序
    }
}
    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct() // 去重
                .sorted()
                .forEach(author -> System.out.println(author.getAge()));
    }

方法二:如果调用有参的 sorted() 方法,则不需要实现 Comparable。

@Data
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
public class Author {
    // id
    private Long id;
    // 姓名
    private String name;
    // 年龄
    private Integer age;
    // 简介
    private String intro;
    // 作品
    private List<Book> books;
}
    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct() // 去重
                .sorted((o1, o2) -> o1.getAge() - o2.getAge())
                .forEach(author -> System.out.println(author.getAge()));
    }
  • limit(long maxSize):可以设置流的长度,超出的部分将被抛弃。

例:对上面的 sorted() 例子进行排序举例:流中超出两个元素过后自动舍弃后面的元素。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct() // 去重
                .sorted((o1, o2) -> o1.getAge() - o2.getAge())
                .limit(2)
                .forEach(author -> System.out.println(author.getAge()));
    }
  • skip(long n):跳过流中的前 n 个元素,返回剩下的元素。

例:打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct() // 去重
                .sorted((o1, o2) -> o2.getAge() - o1.getAge()) // 降序排序
                .skip(1)
                .forEach(author -> System.out.println(author.getAge()));
    }
  • flatMap():map 只能把一个对象转换成另一个对象来作为流中的元素,而 flatMap 可以把一个对象转换成多个对象作为流的元素。

例一:打印所有书籍的名字,要求对重复的元素进行去重。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .forEach(book -> System.out.println(book.getName()));
    }

例二:打印书籍所有的分类,并要求对分类进行去重。

在这里插入图片描述

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .flatMap(book -> Arrays.stream(book.getCategory().split(","))) // 把所有分类按逗号进行分割然后形成集合
                .distinct() // 对集合进行去重
                .forEach(category -> System.out.println(category));
    }

结果:

在这里插入图片描述

3. 方法介绍-终极操作
  • forEach():对流中的元素进行遍历操作,通过传入的参数去指定对遍历的元素进行什么具体的操作。

例:输出所有作家的名字。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getName())
                .distinct()
                .forEach(name -> System.out.println(name));
    }
  • count():获取流中元素的个数。
    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        long count = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .count();
        System.out.println(count);
    }
  • max() & min():分别获取这些作家所出书籍的最高分和最低分进行打印。

最大值max:

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        Optional<Integer> max = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .max((score1, score2) -> score1 - score2); // 此处如果是score2 - score1的话就是最小值
        System.out.println(max.get());
    }

最小值min:

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        Optional<Integer> min= authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .map(book -> book.getScore())
                .min((score1, score2) -> score1 - score2); // 此处如果是score2 - score1的话就是最大值
        System.out.println(min.get());
    }
  • collect():把当前流转换成一个集合。

list集合:获取所有作者的名字,转为list集合存放。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        List<String> collect = authors.stream()
                .map(author -> author.getName())
                .collect(Collectors.toList());
        System.out.println(collect);
    }

set集合:获取所有 book 的 set 集合。

        List<Author> authors = getAuthors();
        Set<Book> collect = authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .collect(Collectors.toSet());
        System.out.println(collect);

map集合:获取一个 map 集合,要求 map 的 key 为作者的名字,value为作者的 List<书籍>。

    public static void main(String[] args) {
    
        List<Author> authors = getAuthors();
        Map<String, List<Book>> map = authors.stream()
                .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
        Stream<Map.Entry<String, List<Book>>> mapStream = map.entrySet().stream();
        mapStream.distinct()
                .forEach(entry -> System.out.println(entry));
    }
  • anyMatch():用来判断是否有任意符合匹配条件的元素,结果为 boolean 类型。

例:判断是否有年龄在 50 岁以上的作家。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        boolean b = authors.stream()
                .anyMatch(author -> author.getAge() > 50);
        System.out.println(b); // false
    }
  • allMatch():用来判断是否满足所有匹配条件的元素,结果为 boolean 类型。

例:判断是否有所有作家都是成年人(年龄都在18以上)。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        boolean b = authors.stream()
                .allMatch(author -> author.getAge() >= 18);
        System.out.println(b); // false
    }
  • noneMatch():用来判断流中的元素是否都不符合匹配条件的元素,结果为 boolean 类型。

例:判断是否所有作家的年龄都超过 100 岁(都不符合结果为 true,否则结果为 false)。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        boolean b = authors.stream()
                .noneMatch(author -> author.getAge() >= 100);
        System.out.println(b); // true
    }
  • findAny():获取流中的任意一个元素,该方法不能保证获取的一定是流中的第一个元素。
  • findFirst():获取流中的第一个元素。
    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        Optional<Author> any = authors.stream()
                .findFirst();
        System.out.println(any.get());
    }
  • reduce():归并,对流中的数据按照制定的计算方式计算出一个结果。

reduce的作用是把流中的元素给结合起来,我们可以传入一个初始值,也可以不传,如果传了初始值,它会按照我们的计算方法依次拿流中的元素和初始值进行计算,这个计算方法可以是加、减、乘、除、找出最大值等等。

当 reduce 传了初始值,既有两个参数时内部的计算方式如下:

     T result = identity;
     for (T element : this stream)
         result = accumulator.apply(result, element)
     return result;

如果对上述计算公式不理解,可以看如下举例:

     int[] arr = {1, 2, 3, 4, 5};
     int result = 1;
     for (int i : arr) {
         /**
          * 此处是自定义的方法,可以自定义加减乘除、作比较等等方法
          */
         result = result * i;
     }

案例:求出所有作家的年龄和。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        Integer sumAge = authors.stream()
                .map(author -> author.getAge())
                .reduce(1, (result, element) -> result + element);
        System.out.println(sumAge); // 打印结果为所有作家年龄和 + 初始值:1
    }

当 reduce 没有初始值,既只有一个参数时内部的计算方式如下:

	 boolean foundAny = false;
     T result = null;
     for (T element : this stream) {
         if (!foundAny) {
             foundAny = true;
             result = element; // 把流中的第一个元素当作的初始值
         }
         else
             result = accumulator.apply(result, element);
     }
     return foundAny ? Optional.of(result) : Optional.empty();

案例:找出所有作家中年龄最大的值。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        Optional<Integer> maxAge = authors.stream()
                .map(author -> author.getAge())
                // 流中第一个元素赋值给了初始值
                .reduce((result, element) -> (result > element) ? result : element);
        System.out.println(maxAge.get());
    }

4. Stream 流注意事项
  • 惰性求值:如果流没有终结操作,中间操作是不会执行的。
  • 流是一次性的:一个流对象经过一个终结操作后,这个流就不能再次使用了,否则会保错。
  • 不会影响原数据:我们在流中对数据进行很多操作后,是不会影响原来流中的元素的。
    案例:对流中作家的年龄都 + 10,但原始作家的年龄还是不会受到影响。
    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getAge())
                .map(age -> age + 10)
                .forEach(age -> System.out.println(age));
        System.out.println("======分割线======");
        authors.stream()
                .map(author -> author.getAge())
                .forEach(age -> System.out.println(age));
    }
    
    结果:
    在这里插入图片描述

五、Optional

1. Optional 概述

我们在编写代码的时候出现最多的就是空指针异常,所以在很多情况下我们需要做各种非空的判断。

例如:

        List<Author> authors = getAuthors();
        if (authors != null) { // 如果getAuthors()中没有元素,就会报空指针异常,所以if判定
            authors.stream()
                    .map(author -> author.getName())
                    .forEach(name -> System.out.println(name)); 
        }

这种过多的判断语句会让我们的代码显得臃肿,所以在 JDK8 中引入了 Optional,养成使用 Optional 的习惯后可以写出更优雅的代码来避免空指针异常。并且在很多函数式编程相关的 API 中也都用到了Optional,如果不会使用Oplional也会对函数式编程的学习造成影响。


2. 使用
  • 创建对象:Optional就好像是包装类,可以把我们的具体数据封装在 Optional 对象内部,然后我们去使用 Optional 中封装好的方法操作封装进去的数据,可以非常优雅的避免空指针异常。

一般使用 Optional 的静态方法:ofNullable 来把数据封装成一个 Optional 对象,无论传入的参数是否为 null 都不会出现问题。如果确定了 getAuthors 不为空,则可以使用 Optional 的静态方法:of() 封装 Optional 对象。

案例:

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        Optional<List<Author>> optionalAuthors = Optional.ofNullable(authors); // getAuthors()为null也不报空指针异常,因为已经做了判断处理
        optionalAuthors.ifPresent(authors1 -> authors1.stream().forEach(author -> System.out.println(author.getName())));
    }

如果非常确定 getAuthors() 不为 null,则可以使用 Optional 的 of() 方法。使用 of() 方法,如果 authors 为 null 则会报空指针异常。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        Optional<List<Author>> optionalAuthors = Optional.of(authors);
        optionalAuthors.ifPresent(authors1 -> authors1.stream().forEach(author -> System.out.println(author.getName())));
    }

此处如果觉得在操作 getAuthors() 数据时,多写了这行代码: Optional<List> optionalAuthors = Optional.ofNullable(authors); 也比较麻烦(类似于也没没有达到代码的优雅程度),则可以在 getAuthors() 返回数据时直接返回 Optional 对象的数据。

    private static Optional<ArrayList<Author>> getAuthors() {
		// ......
        return Optional.ofNullable(authors);
    }

如果我们的方法返回类型已经固定是 Optional 了,但是数据也确定为 null,则可以返回 Optional.empty();


  • 安全消费值:我们获取到一个 Optional 对象后需要对其中的数据进行使用。这时我们可以使用 ifPresent() 方法来进行消费。这个方法会判断其内封装的数据是否为空,不为空使才会执行具体的消费代码,这样使用就更加安全了。

例如:以下写法就优雅的避免了空指针异常。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        Optional<List<Author>> optionalAuthors = Optional.ofNullable(authors);
        optionalAuthors.ifPresent(authors1 -> authors1.stream().forEach(author -> System.out.println(author.getName())));
    }

  • 获取值:如果我们想获取值可以使用 get() 方法获取,但是不推荐,因为 Optional 内部的数据为空的时候会出现异常。采用如下 Optional 提供的方法安全获取值。

    • orElseGet:获取数据并且设置数据为空时的默认值,如果数据不为空就能获取到该数据,如果为空则根据传入的参数作为默认值返回。

          private static Optional<List<Author>> getAuthors() {
        		return Optional.ofNullable(null); // 故意设置为null
        	}
        	
        	Optional<List<Author>> authors = getAuthors();
          List<Author> authorList = authors.orElseGet(new Supplier<List<Author>>() {
               @Override
               public List<Author> get() {
                   ArrayList<Author> list = new ArrayList<>();
                   list.add(new Author(3l, "佚名", 88, "简介", null));
                   return list;
               }
           });
           System.out.println(authorList);	
      

      在这里插入图片描述

    • orElseThrow:获取数据,如果数据不为空就能获取到该数据,如果为空则根据传入的参数来创建异常抛出。

          public static void main(String[] args) {
              Optional<List<Author>> authors = getAuthors();
              try {
                  authors.orElseThrow(new Supplier<Throwable>() {
                      @Override
                      public Throwable get() {
                          return new RuntimeException("数据为空");
                      }
                  });
              } catch (Throwable throwable) {
                  throwable.printStackTrace();
              }
      	}
      

      在这里插入图片描述

  • filiter():过滤,Optional 的 filiter 过滤方法很鸡肋,基本起不到什么过滤的作用,此处直接省略。

  • 判断方法:使用 isPresent 方法可以判断数据是否存在,如果为空在返回 false,不为空则返回 true。但是这种方法不能体现 Optional 的好处,更推荐使用 ifPresent 方法。


六、函数式接口

只有一个抽象方法的接口我们称之为函数接口。
JDK 的函数式接口都加上了@Functionallnterface 注解进行标识,但是无论是否加上该注解只要接口中只有一个抽象方法,都是的数式接口。

  • 常用函数式接口

    • Consumer 消费接口:根据抽象方法的参数列表和返回值类型,我们可以在方法中对传入的参数进行消费。
    @FunctionalInterface
    public interface Consumer<T> {
        void accept(T t);
    

    ====================== 关于函数式接口此处就不过多演示 =====================

  • 方法引用:我们在使用 lambda 时,如果方法体中只有一个方法的调用的话(包括构造方法),我们可以用方法引用进一步简化代码。

不需要考虑什么时候用方法引用、用哪种方法引用、方法引用的格式是什么,我们只需要在写完 lambda 方法后,发现方法体只有一行代码,并且是方法的调用时使用快捷键尝试是否能够换成方法引用即可。

基本格式:

类名或对象名::方法名

第一种用法:引用类的静态方法。

如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的静态方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个静态方法中,这个时候我们就可以引用类的静态方法。

案例一:

    public static void main(String[] args) {
       List<Author> authors = getAuthors();
       authors.stream()
               .map(author -> author.getAge())
               .map(new Function<Integer, Object>() {
                   @Override
                   public Object apply(Integer age) {
                       return String.valueOf(age); // String类的静态方法
                   }
               });
   }

转换后:

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getAge())
                .map((Function<Integer, Object>) String::valueOf);
    }

第二种用法:引用对象的实例方法。

如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个对象的成员变量,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用对象的实例方法。

案例二:

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        StringBuilder sb = new StringBuilder();
        authors.stream()
                .map(author -> author.getName())
                .forEach(new Consumer<String>() {
                    @Override
                    public void accept(String name) {
                        sb.append(name); // 对象的实例方法
                    }
                });
    }

转换后:

    public static void main(String[] args) {
       List<Author> authors = getAuthors();
       StringBuilder sb = new StringBuilder();
       authors.stream()
               .map(author -> author.getName())
               .forEach(sb::append);
   }

第三种用法:引用类的实例方法。

如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了第一个参数的成员方法。并且我们把要重写的抽象方法中剩余的所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用类的实例方法。

案例三:

    interface UseString {
        String use(String str, int start, int length);
    }

    public static String subAuthorName(String str, UseString useString) {
        int start = 0;
        int length = 1;
        return useString.use(str, start, length);
    }

    public static void main(String[] args) {
        subAuthorName("张三", new UseString() {
            @Override
            public String use(String str, int start, int length) { // 类的实例方法
                return str.substring(start, length);
            }
        });
    }

转换后:

    interface UseString {
        String use(String str, int start, int length);
    }

    public static String subAuthorName(String str, UseString useString) {
        int start = 0;
        int length = 1;
        return useString.use(str, start, length);
    }

    public static void main(String[] args) {
        subAuthorName("张三", String::substring);
    }

总结:实际上不管是哪种方法,都不用刻意去纠结,也不用太刻意的去记,只要是方法体中只有一行代码,都可以使用快捷键去生成方法引用的代码。

  • 构造器引用:如果方法体中的一行代码是构造器,则可以直接使用构造器引用。

基本格式:

类名::new

如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是某个方法的构造方法,并且我们把要重写的抽象方法中的所有的参数都按照顺序传入了这个构造方法中,这个时候我们就可以引用构造器。

案例:

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getName())
                .map(name -> new StringBuilder(name)) // StringBuilder的构造方法
                .map(sb -> sb.append("张三").toString())
                .forEach(str -> System.out.println(str));
    }

转换后:

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getName())
                .map(StringBuilder::new) // 构造方法处
                .map(sb -> sb.append("张三").toString())
                .forEach(System.out::println); // 构造方法处
    }

七、高级用法 - 基本数据类型优化

我们之前用到的很多 Stream 的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。

即使我们操作的是整教小数,但是实际用的都是他们的包装类。JDK5 中引入的自动装箱和自动近箱让我们在使用对应的包装类时就好修使用基本数想类型一样方便,但是我们也一定要知道装箱和拆箱都是需要消样时间的。虽然这个时间消耗很小,但在大量的数据在不断的重复装箱拆箱的时候,我们就不能忽视这个时间损耗。

所以为了让我们能够对这部分的时间消耗进行优化。Stream 还提供了很多专门针对基本数据类型的方法。

例如:mapTolnt,mapTolong,mapToDouble,flatMapTolnt,flatMapToDouble 等。

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .map(author -> author.getAge())
                .map(age -> age + 10)
                .filter(age -> age > 18)
                .map(age -> age + 2)
                .forEach(System.out::println);
    }

变换后:

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .mapToInt(author -> author.getAge())  // 此处做了改造,效率变高
                .map(age -> age + 10)
                .filter(age -> age > 18)
                .map(age -> age + 2)
                .forEach(System.out::println);
    }

八、并行流(简单介绍)

当流中有大量元素时,我们可以使用并行流去提高操作的效率。其实并行流就是把任务分配给多个线程去处理。如果我们自己用代码去实现的话其实会非常的复杂,并且要求对并发编程有足够的理解和认识,而如果我们使用Stream 的话,我们只需要修改一个方法的调用就可以使用并行流来帮我们实现,从而提高效率。

    public static void main(String[] args) {
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Integer sum = integerStream.parallel() // 加.parallel()就是并行流
                .filter(num -> num > 5)
                .reduce((result, ele) -> result + ele)
                .get();
        System.out.println(sum);
    }

或者直接定义:parallelStream()。

        List<Author> authors = getAuthors();
        authors.parallelStream()
                .mapToInt(author -> author.getAge())
                .map(age -> age + 10)
                .filter(age -> age > 18)
                .map(age -> age + 2)
                .forEach(System.out::println);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值