java8重点新特性——stream流与方法引用

一、Stream流

1.1 概述

Stream(流)是一个来自数据源的元素队列并支持聚合操作

  1. 元素是特定类型的对象,形成一个队列。 Java中的Stream并不会存储元素,而是按需计算。
  2. 数据源:流的来源。 可以是集合,数组,I/O channel, 产生器generator 等。
  3. 聚合操作:类似SQL语句一样的操作, 比如filter, map, reduce, find, match, sorted等。

和以前的Collection操作不同, Stream操作还有两个基础的特征:

  1. Pipelining: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。这样做可以对操作进行优化, 比如延迟执行(laziness)和短路( short-circuiting)。
  2. 内部迭代:以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式, 通过访问者模式(Visitor)实现。

当使用一个流的时候,通常包括三个基本步骤:获取一个数据源(source)→ 数据转换→执行操作获取想要的结果,每次转换原有 Stream 对象不改变,返回一个新的 Stream 对象(可以有多次转换),这就允许对其操作可以像链条一样排列,变成一个管道。

1.2 获取流

java.util.stream.Stream 是Java 8新加入的最常用的流接口。(这并不是一个函数式接口。)
获取一个流非常简单,有以下几种常用的方式:

  • 所有的 Collection 集合都可以通过 stream 默认方法获取流;
  • Stream 接口的静态方法 of 可以获取数组对应的流。
根据Collection获取流

java.util.Collection 接口中加入了default方法 stream 用来获取流,所以其所有实现类均可获取流。

public class stream {
    
    
    public static void main(String[] args) {
    
    
        List<String> list = new ArrayList<>();
        Stream<String> s1 = list.stream();

        Set<Object> set = new HashSet<>();
        Stream<Object> s2 = set.stream();

        Vector<Object> vector = new Vector<>();
        Stream<Object> s3 = vector.stream();
    }
}
根据Map获取流

java.util.Map 接口不是 Collection 的子接口,且其K-V数据结构不符合流元素的单一特征,所以获取对应的流
需要分key、value或entry等情况:

public class streamMap {
    
    
    public static void main(String[] args) {
    
    
        Map<Object, Object> map = new HashMap<>();
        Stream<Object> keyStream = map.keySet().stream();
        Stream<Object> valueStream = map.values().stream();
        Set<Map.Entry<Object, Object>> entryStream = map.entrySet();
    }
}
根据数组获取流

如果使用的不是集合映射而是数组,因数组对象不可能添加默认方法,所以 Stream 接口中提供了静态方法of ,使用很简单:

public class y03streamArray {
    
    
    public static void main(String[] args) {
    
    
        int[] array = {
    
    10,30,20};
        Stream<int[]> stream = Stream.of(array);
    }
}

备注: of 方法的参数其实是一个可变参数,所以支持数组。

1.3 常用方法

流模型的操作很丰富,这里介绍一些常用的API。这些方法可以被分成两种:

  • 延迟方法:返回值类型仍然是 Stream 接口自身类型的方法,因此支持链式调用。(除了终结方法外,其余方法均为延迟方法。)
  • 终结方法:返回值类型不再是 Stream 接口自身类型的方法,因此不再支持类似 StringBuilder
    那样的链式调用。本小节中,终结方法包括 count 和 forEach 方法。

备注:还有更多方法,请自行参考API文档。

forEach

虽然方法名字叫 forEach ,但是与for循环中的“for-each”昵称不同。

void forEach(Consumer<? super T> action);

该方法接收一个 Consumer 接口函数,会将每一个流元素交给该函数进行处理。

复习Consumer接口

java.util.function.Consumer<T>接口是一个消费型接口。
Consumer接口中包含抽象方法void accept(T t),意为消费一个指定泛型的数据。

基本使用

public class y04forEach {
    
    
    public static void main(String[] args) {
    
    
        String[] array = {
    
    "ltd","xpr","lanyou"};
        Stream.of(array).forEach(s -> System.out.println(s));
    }
}
过滤 filter

可以通过 filter 方法将一个流转换成另一个子集流。方法签名:

Stream<T> filter(Predicate<? super T> predicate);

该接口接收一个 Predicate 函数式接口参数(可以是一个Lambda或方法引用)作为筛选条件。

复习Predicate接口
java.util.stream.Predicate 函数式接口,其中唯一的抽象方法为:

boolean test(T t);

该方法将会产生一个boolean值结果,代表指定的条件是否满足。如果结果为true,那么Stream流的 filter 方法将会留用元素;如果结果为false,那么 filter 方法将会舍弃元素。

基本使用
Stream流中的 filter 方法基本使用的代码如:

public class y05filter {
    
    
    public static void main(String[] args) {
    
    
        String[] array = {
    
    "科比","哈登","库里"};
        Stream<String> stream = Stream.of(array).filter(s -> s.startsWith("哈"));
        
        stream.forEach(s -> System.out.println(s));
    }
}

在这里通过Lambda表达式来指定了筛选的条件:必须以“哈”开头。

映射 map

如果需要将流中的元素映射到另一个流中,可以使用 map 方法。方法签名:

<R> Stream<R> map(Function<? super T, ? extends R> mapper);

该接口需要一个 Function 函数式接口参数,可以将当前流中的T类型数据转换为另一种R类型的流。

复习Function接口
java.util.stream.Function 函数式接口,其中唯一的抽象方法为:

R apply(T t);

这可以将一种T类型转换成为R类型,而这种转换的动作,就称为“映射”。

基本使用
Stream流中的 map 方法基本使用的代码如:

public class y06map {
    
    
    public static void main(String[] args) {
    
    
        String[] array = {
    
    "20","15","25"};
        Stream<Integer> stream = Stream.of(array).map(s -> Integer.parseInt(s));

        stream.forEach(s -> System.out.println(s));
    }
}

这段代码中, map 方法的参数通过方法引用,将字符串类型转换成为了int类型(并自动装箱为 Integer 类对象)。

统计个数 count

正如旧集合 Collection 当中的 size 方法一样,流提供 count 方法来数一数其中的元素个数:

long count();

该方法返回一个long值代表元素个数(不再像旧集合那样是int值)。基本使用:

public class y07count {
    
    
    public static void main(String[] args) {
    
    
        String[] array = {
    
    "詹姆斯","科比","奥尼尔"};
        Stream.of(array).count();
    }
}
取用前几个 limit

limit 方法可以对流进行截取,只取用前n个。方法签名:

Stream<T> limit(long maxSize);

参数是一个long型,如果集合当前长度大于参数则进行截取;否则不进行操作。基本使用:

public class y08limit {
    
    
    public static void main(String[] args) {
    
    
        String[] array = {
    
    "詹姆斯","科比","奥尼尔"};
        System.out.println(Stream.of(array).limit(2).count());  // 输出2
    }
}
跳过前几个 skip

如果希望跳过前几个元素,可以使用 skip 方法获取一个截取之后的新流:

Stream<T> skip(long n);

如果流的当前长度大于n,则跳过前n个;否则将会得到一个长度为0的空流。基本使用:

public class y09skip {
    
    
    public static void main(String[] args) {
    
    
        String[] array = {
    
    "胡歌","霍建华","彭于晏","吴彦祖"};
        Stream<String> skip = Stream.of(array).skip(2);
        skip.forEach(s -> System.out.println(s));   // 输出彭于晏 吴彦祖
    }
}
组合 concat

如果有两个流,希望合并成为一个流,那么可以使用 Stream 接口的静态方法 concat :

static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)

备注:这是一个静态方法,与 java.lang.String 当中的 concat 方法是不同的。

该方法的基本使用代码如:

public class y10concat {
    
    
    public static void main(String[] args) {
    
    
        String[] a1 = {
    
    "胡歌","彭于晏"};
        String[] a2 = {
    
    "吴彦祖","霍建华"};
        Stream<String> s1 = Stream.of(a1);
        Stream<String> s2 = Stream.of(a2);
        Stream.concat(s1,s2).forEach(s -> System.out.println(s));   // 依次输出:胡歌 彭于晏 吴彦祖 霍建华
    }
}

二、方法引用

在使用Lambda表达式的时候,我们实际上传递进去的代码就是一种解决方案:拿什么参数做什么操作。那么考虑
一种情况:如果我们在Lambda中所指定的操作方案,已经有地方存在相同方案,那是否还有必要再写重复逻辑?

2.1 冗余的Lambda场景

一个简单的函数式接口以应用Lambda表达式:

@FunctionalInterface
public interface Printable {
    
    
   void print(String str);  
}

在 Printable 接口当中唯一的抽象方法 print 接收一个字符串参数,目的就是为了打印显示它。那么通过Lambda
来使用它的代码很简单:

public class y11method {
    
    
    public static void main(String[] args) {
    
    
        printString(str -> System.out.println(str));
    }

    private static void printString(y11functionInterface.Printable printable){
    
    
        printable.print("ltd");
    }
}

其中 printString 方法只管调用 Printable 接口的 print 方法,而并不管 print 方法的具体实现逻辑会将字符串打印到什么地方去。而 main 方法通过Lambda表达式指定了函数式接口 Printable 的具体操作方案为:拿到String(类型可推导,所以可省略)数据后,在控制台中输出它。

2.2 问题分析

这段代码的问题在于,对字符串进行控制台打印输出的操作方案,明明已经有了现成的实现,那就是 System.out
对象中的 println(String) 方法。既然Lambda希望做的事情就是调用 println(String) 方法,那何必自己手动调
用呢?

2.3 用方法引用改进代码

能否省去Lambda的语法格式(尽管它已经相当简洁)呢?只要“引用”过去就好了:

public class y11method {
    
    
    public static void main(String[] args) {
    
    
        printString(System.out::print);
    }

    private static void printString(y11functionInterface.Printable printable){
    
    
        printable.print("ltd");
    }
}

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

2.4 方法引用符

双冒号 :: 为引用运算符,而它所在的表达式被称为方法引用。如果Lambda要表达的函数方案已经存在于某个方
法的实现中,那么则可以通过双冒号来引用该方法作为Lambda的替代者。

语义分析
例如上例中, System.out 对象中有一个重载的 println(String) 方法恰好就是我们所需要的。那么对于
printString 方法的函数式接口参数,对比下面两种写法,完全等效:

  • Lambda表达式写法: s -> System.out.println(s);
  • 方法引用写法: System.out::println

第一种语义是指:拿到参数之后经Lambda之手,继而传递给 System.out.println 方法去处理。
第二种等效写法的语义是指:直接让 System.out 中的 println 方法来取代Lambda。两种写法的执行效果完全一
样,而第二种方法引用的写法复用了已有方案,更加简洁。
注:Lambda 中 传递的参数 一定是方法引用中 的那个方法可以接收的类型,否则会抛出异常

推导与省略
如果使用Lambda,那么根据“可推导就是可省略”的原则,无需指定参数类型,也无需指定的重载形式——它们都
将被自动推导。而如果使用方法引用,也是同样可以根据上下文进行推导。

函数式接口是Lambda的基础,而方法引用是Lambda的孪生兄弟。

下面这段代码将会调用 println 方法的不同重载形式,将函数式接口改为int类型的参数:

@FunctionalInterface
public interface y12PrintableInteger {
    
    
   void print(int str);  
}

由于上下文变了之后可以自动推导出唯一对应的匹配重载,所以方法引用没有任何变化:

public class y12PrintOverload {
    
    
    private static void printInteger(PrintableInteger data) {
    
    
       data.print(1024);  
    }
    public static void main(String[] args) {
    
    
       printInteger(System.out::println);  
    }
}

这次方法引用将会自动匹配到 println(int) 的重载形式。

2.5 通过对象名引用成员方法

这是最常见的一种用法,与上例相同。如果一个类中已经存在了一个成员方法:

public class y12methodRefObject {
    
    
    public void printUpperCase(String str){
    
    
        System.out.println(str.toUpperCase());
    }
}

函数式接口仍然定义为:

@FunctionalInterface
public interface y12functionInterface {
    
    
    void print(String str);
}

那么当需要使用这个 printUpperCase 成员方法来替代 Printable 接口的Lambda的时候,已经具有了MethodRefObject 类的对象实例,则可以通过对象名引用成员方法,代码为:

public class y12methodRef {
    
    
    private static void printString(y12functionInterface print){
    
    
        print.print("ltd");
    }

    public static void main(String[] args) {
    
    
        y12methodRefObject methodRefObject = new y12methodRefObject();
        printString(methodRefObject::printUpperCase);
    }
}

2.6 通过类名称引用静态方法

由于在 java.lang.Math 类中已经存在了静态方法 abs ,所以当我们需要通过Lambda来调用该方法时,有两种写
法。首先是函数式接口:

@FunctionalInterface
public interface y13functionInterface {
    
    
    int calc(int num);
}

第一种写法是使用Lambda表达式:

public class y13lambda {
    
    
    private static void method(int num, y13functionInterface lambda){
    
    
        System.out.println(lambda.calc(num));
    }

    public static void main(String[] args) {
    
    
        method(-10, s -> Math.abs(s));
    }
}

但是使用方法引用的更好写法是:

public class y13lambda {
    
    
    private static void method(int num, y13functionInterface lambda){
    
    
        System.out.println(lambda.calc(num));    
    }

    public static void main(String[] args) {
    
    
        method(10, Math::abs);
    }
}

在这个例子中,下面两种写法是等效的:

  • Lambda表达式: n -> Math.abs(n)
  • 方法引用: Math::abs

2.7 通过super引用成员方法

如果存在继承关系,当Lambda中需要出现super调用时,也可以使用方法引用进行替代。首先是函数式接口:

@FunctionalInterface
public interface Greetable {
    
    
   void greet();  
}

然后是父类 Human 的内容:

public class Human {
    
    
    public void sayHello() {
    
    
       System.out.println("Hello!");  
    }
}

最后是子类 Man 的内容,其中使用了Lambda的写法:

public class Man extends Human {
    
    
    @Override
    public void sayHello() {
    
    
        System.out.println("大家好,我是Man!");
    }
    //定义方法method,参数传递Greetable接口
    public void method(Greetable g){
    
    
        g.greet();
    }
    public void show(){
    
    
        //调用method方法,使用Lambda表达式
        method(()>{
    
    
            //创建Human对象,调用sayHello方法
            new Human().sayHello();
        });
        //简化Lambda
        method(()>new Human().sayHello());
        //使用super关键字代替父类对象
        method(()>super.sayHello());
    }
}

但是如果使用方法引用来调用父类中的 sayHello 方法会更好,例如另一个子类 Woman :

public class Man extends Human {
    
    
    @Override
    public void sayHello() {
    
    
        System.out.println("大家好,我是Man!");
    }
    //定义方法method,参数传递Greetable接口
    public void method(Greetable g){
    
    
        g.greet();
    }
    public void show(){
    
    
        method(super::sayHello);
    }
}

在这个例子中,下面两种写法是等效的:

  • Lambda表达式: () -> super.sayHello()
  • 方法引用: super::sayHello

2.8 通过this引用成员方法

this代表当前对象,如果需要引用的方法就是当前类中的成员方法,那么可以使用“this::成员方法”的格式来使用方
法引用。首先是简单的函数式接口:

@FunctionalInterface
public interface Richable {
    
    
   void buy(); 
}

下面是一个丈夫 Husband 类:

public class Husband {
    
    
    private void marry(Richable lambda) {
    
    
       lambda.buy();  
    }
    public void beHappy() {
    
    
       marry(()> System.out.println("买套房子"));  
    }
}

开心方法 beHappy 调用了结婚方法 marry ,后者的参数为函数式接口 Richable ,所以需要一个Lambda表达式。
但是如果这个Lambda表达式的内容已经在本类当中存在了,则可以对 Husband 丈夫类进行修改:

public class Husband {
    
    
    private void buyHouse() {
    
    
       System.out.println("买套房子");  
    }
    private void marry(Richable lambda) {
    
    
       lambda.buy();  
    }
    public void beHappy() {
    
    
       marry(()> this.buyHouse());  
    }
}

如果希望取消掉Lambda表达式,用方法引用进行替换,则更好的写法为:

public class Husband {
    
    
    private void buyHouse() {
    
    
       System.out.println("买套房子");  
    }
    private void marry(Richable lambda) {
    
    
       lambda.buy();  
    }
    public void beHappy() {
    
    
       marry(this::buyHouse);  
    }
}

在这个例子中,下面两种写法是等效的:

  • Lambda表达式: () -> this.buyHouse()
  • 方法引用: this::buyHouse

2.9 类的构造器引用

由于构造器的名称与类名完全一样,并不固定。所以构造器引用使用 类名称::new 的格式表示。首先是一个简单
的 Person 类:

public class Person {
    
    
    private String name;
    public Person(String name) {
    
    
        this.name = name;
    }
    public String getName() {
    
    
        return name;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
}

然后是用来创建 Person 对象的函数式接口:

public interface PersonBuilder {
    
    
    Person buildPerson(String name);
}

要使用这个函数式接口,可以通过Lambda表达式:

public class Demo09Lambda {
    
    
    public static void printName(String name, PersonBuilder builder) {
    
    
       System.out.println(builder.buildPerson(name).getName());  
    }
    public static void main(String[] args) {
    
    
       printName("赵丽颖", name ‐> new Person(name));  
    }
}

但是通过构造器引用,有更好的写法:

public class Demo10ConstructorRef {
    
    
    public static void printName(String name, PersonBuilder builder) {
    
    
       System.out.println(builder.buildPerson(name).getName());  
    }
    public static void main(String[] args) {
    
    
       printName("赵丽颖", Person::new);  
    }
}

在这个例子中,下面两种写法是等效的:

  • Lambda表达式: name -> new Person(name)
  • 方法引用: Person::new

2.10 数组的构造器引用

数组也是 Object 的子类对象,所以同样具有构造器,只是语法稍有不同。如果对应到Lambda的使用场景中时,
需要一个函数式接口:

@FunctionalInterface
public interface ArrayBuilder {
    
    
   int[] buildArray(int length);  
}

在应用该接口的时候,可以通过Lambda表达式:

public class Demo11ArrayInitRef {
    
      
    private static int[] initArray(int length, ArrayBuilder builder) {
    
    
       return builder.buildArray(length);  
    }
    public static void main(String[] args) {
    
    
       int[] array = initArray(10, length ‐> new int[length]);  
    }
}

但是更好的写法是使用数组的构造器引用:

public class Demo12ArrayInitRef {
    
    
    private static int[] initArray(int length, ArrayBuilder builder) {
    
    
       return builder.buildArray(length);  
    }
    public static void main(String[] args) {
    
    
       int[] array = initArray(10, int[]::new);  
    }
}

在这个例子中,下面两种写法是等效的:

  • Lambda表达式: length -> new int[length]
  • 方法引用: int[]::new

猜你喜欢

转载自blog.csdn.net/Xyouzi/article/details/112847372
今日推荐