Java foundation -Stream flow method cited articles

1. Stream flow

Speaking Stream it is easy to think of I / O Stream, in fact, who prescribed "flow" it must be "IO stream" mean? In Java 8 in, thanks to functional programming Lambda brought about by the introduction of a new concept of Stream, has been used to solve the drawbacks of the existing library collections.

1.1 Introduction

Conventional multi-step through code set

Almost all of the set (e.g., Map Collection interface or interfaces, etc.) are directly or indirectly support the traversal operations. And when we need to operate elements of the collection, in addition to adding necessary, Delete, Get, the most typical is a collection of traversal. E.g:

import java.util.ArrayList;
import java.util.List;
public class Demo01ForEach {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("周芷若");
        list.add("赵敏");
        list.add("张强");
        list.add("张三丰");
        for (String name : list) {
        System.out.println(name);
        }
    }
}

This is a very simple set of traversal operations: each of the set of strings are a print output operation.

Loop through drawbacks

Java Lambda 8 so that we can focus more on what to do (the What) , rather than how to do (How) . Now, we carefully understand what the example code, you can find:

  • for loop syntax is "how to do"
  • Loop for loop is the "what"

Why cycling? Because to be traversed. But cycling is the only way to traverse it? Traversing means for processing each element individually, and not from the first cycle to the last of the sequential processing. The former is the goal, which is the way.

Imagine, if you want to set filter element filter:

  1. A set according to conditions of the filter as a subset of B;
  2. The second condition and then filtered subset C.

How to do that? In practice before 8 Java might be:

import java.util.ArrayList;
import java.util.List;
public class Demo02NormalFilter {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("周芷若");
        list.add("赵敏");
        list.add("张强");
        list.add("张三丰");
        List<String> zhangList = new ArrayList<>();
        for (String name : list) {
            if (name.startsWith("张")) {
                zhangList.add(name);
            }
        }
        List<String> shortList = new ArrayList<>();
        for (String name : zhangList) {
            if (name.length() == 3) {
            shortList.add(name);
            }
        }
        for (String name : shortList) {
            System.out.println(name);
        }
    }
}

This code contains three cycles, each of a different function:

  1. Zhang's first screened all people;
  2. Then there are the names of people screened three words;
  3. Finally, the results printout.

Whenever we need to set the elements to operate, always need to cycle, cycle, recycle. It is only natural it? No. Cycling is a way of doing things, not an end. On the other hand, using a linear traversal cycle means that only once. If you want to traverse again, and then use another cycle can only start from scratch. That, Lambda derivatives Stream can bring us what more elegant wording it?

Stream more preferably wording

The following look at Java Stream API 8 of aid, what is meant by elegant:

import java.util.ArrayList;
import java.util.List;
public class Demo03StreamFilter {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("周芷若");
        list.add("赵敏");
        list.add("张强");
        list.add("张三丰");
        list.stream()
        .filter(s ‐> s.startsWith("张"))
        .filter(s ‐> s.length() == 3)
        .forEach(System.out::println);
    }
}

Reading the code directly to the literal meaning of the semantic perfect display of logically independent: an acquisition stream, Zhang was filtered, the filter length is 3, the printing one by one. The code does not reflect the use of linear cyclic or any other algorithm to traverse, we really need to do is to better reflect the contents of the code.

1.2 Streaming thought

Note: Please Forget the stereotype of the traditional IO streams!

Overall, the idea is similar to the factory floor flow "production line."

!01.jpg

When the need for multiple elements to operate (especially multi-step operation), taking into account performance and convenience, we should first of all a good fight a "model" step program, and then follow the program to execute it.

02.jpg

This is shown in FIG filtering, mapping, skip, counting multiple operations, it is a process scheme of a collection of elements, while the program is a "function model." FIG Each block is a "flow", the method invokes the specified, another flow may be a flow model from the model conversion. The rightmost digit 3 is the final result.

Here the filter, map, skip to the function model are in operation, and the collection element is not actually processed. Only when the count termination method of execution, the entire operation will be performed in accordance with the model specified policy. And thanks to the delay in the implementation of the Lambda characteristic.

"Stream Flow" is actually a collection of elements of the model function, it is not set, the data structure is not, in itself does not store any element (or address value).

Stream (flow) is an element of the queue elements from the data source is a particular type of object, a queue is formed. In Java Stream and does not store elements, but on-demand computing. Origin of the data source. It may be a collection, such as an array.

Collection different previous operation, Stream operation there are two basic characteristics:

  1. PIPELINING : intermediate operations return stream object itself. Such operations may be connected in series to a plurality of pipes, as flow style (fluent style). This will optimize the operation, such as delayed execution (laziness) and short circuit (short-circuiting).
  2. 内部迭代: 以前对集合遍历都是通过Iterator或者增强for的方式, 显式的在集合外部进行迭代, 这叫做外部迭 代。 Stream提供了内部迭代的方式,流可以直接调用遍历方法。

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

1.3 获取流

java.util.stream.Stream 是Java 8新加入的最常用的流接口。(这并不是一个函数式接口。)

获取一个流非常简单,有以下几种常用的方式:

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

根据Collection获取流

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

import java.util.*;
import java.util.stream.Stream;
public class Demo04GetStream {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        // ...
        Stream<String> stream1 = list.stream();
        Set<String> set = new HashSet<>();
        // ...
        Stream<String> stream2 = set.stream();
        Vector<String> vector = new Vector<>();
        // ...
        Stream<String> stream3 = vector.stream();
    }
}

根据Map获取流

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

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public class Demo05GetStream {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        // ...
        Stream<String> keyStream = map.keySet().stream();
        Stream<String> valueStream = map.values().stream();
        Stream<Map.Entry<String, String>> entryStream = map.entrySet().stream();
    }
}

根据数组获取流

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

import java.util.stream.Stream;
public class Demo06GetStream {
    public static void main(String[] args) {
        String[] array = { "张无忌", "张翠山", "张三丰", "张一元" };
        Stream<String> stream = Stream.of(array);
    }
}

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

1.4 常用方法

03.jpg

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

延迟方法:返回值类型仍然是 Stream 接口自身类型的方法,因此支持链式调用。(除了终结方法外,其余方 法均为延迟方法。)

终结方法:返回值类型不再是 Stream 接口自身类型的方法,因此不再支持类似 StringBuilder 那样的链式调 用。本小节中,终结方法包括 count 和 forEach 方法。

逐一处理:forEach

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

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

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

java.util.function.Consumer<T>接口是一个消费型接口。
Consumer接口中包含抽象方法void accept(T t),意为消费一个指定泛型的数据。
基本使用
public class Test01 {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("张三");
    list.add("李四");
    list.add("王五");
    list.stream().forEach(name-> System.out.println(name));
  }
}

过滤:filter

04.jpg

可以通过 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 Test02 {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("张三");
    list.add("李四");
    list.add("张三丰");
    list.add("王五");
    list.add("张无忌");
    list.stream()
            .filter(name->name.startsWith("张"))
            .forEach(name-> System.out.println(name));
  }
}

在这里通过Lambda表达式来指定了筛选的条件:必须姓张。

映射:map

05.jpg

如果需要将流中的元素映射到另一个流中,可以使用 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类型,而这种转换的动作,就称为“映射”

基本使用
public class Test03 {
  public static void main(String[] args) {
    String[]strs = {"11","22","33","44"};
    Stream.of(strs)
            .map((s -> Integer.parseInt(s)))
            .forEach(i-> System.out.println(i+2));
  }
}

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

统计个数:count

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

long count();

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

  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("张三");
    list.add("李四");
    list.add("张三丰");
    list.add("王五");
    list.add("张无忌");
    long i = list.stream()
            .filter(name->name.startsWith("张"))
            .count();
    System.out.println(i);//3
  }

取用前几个:limit

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

Stream<T> limit(long maxSize);

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

public class Test06 {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("张三");
    list.add("李四");
    list.add("张三丰");
    list.add("王五");
    list.add("张无忌");
    list.stream()
            .filter(name->name.startsWith("张"))
            .limit(2)
            .forEach(name-> System.out.println(name));
  }
}
// 结果-张三、张三丰

跳过前几个:skip

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

Stream<T> skip(long n);

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

07.jpg

public class Test07 {
  public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("张三");
    list.add("李四");
    list.add("张三丰");
    list.add("王五");
    list.add("张无忌");
    list.stream()
            .filter(name->name.startsWith("张"))
            .skip(2)
            .forEach(name-> System.out.println(name));
  }
}
// 结果:张无忌

组合:concat

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

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

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

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

public class Test08 {
  public static void main(String[] args) {
    Stream<String>  s1 = Stream.of("张三","李四");
    Stream<String>  s2 = Stream.of("王五","赵六");
    Stream.concat(s1,s2).forEach(name-> System.out.println(name));
  }
}
// 结果:张三、李四、王五、赵六

2. 方法引用

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

2.1 冗余的Lambda场景

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

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

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

public class Demo01PrintSimple {
    private static void printString(Printable data) {
     data.print("Hello, World!");
    }
    public static void main(String[] args) {
     printString(s ‐> System.out.println(s));
    }
}

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

2.2 问题分析

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

2.3 用方法引用改进代码

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

public class Demo02PrintRef {
    private static void printString(Printable data) {
        data.print("Hello, World!");
    }
    public static void main(String[] args) {
        printString(System.out::println);
    }
}

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

2.4方法引用符

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

语义分析

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

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

第一种语义是指:拿到参数之后经Lambda之手,继而传递给 System.out.println 方法去处理。 第二种等效写法的语义是指:直接让 System.out 中的 println 方法来取代Lambda。两种写法的执行效果完全一 样,而第二种方法引用的写法复用了已有方案,更加简洁。

注:Lambda 中 传递的参数 一定是方法引用中 的那个方法可以接收的类型,否则会抛出异常

推导与省略

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

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

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

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

public class Demo03PrintOverload {
    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 MethodRefObject {
    public void printUpperCase(String str) {
        System.out.println(str.toUpperCase());
    }
}

函数式接口仍然定义为:

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

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

public class Demo04MethodRef {
    private static void printString(Printable lambda) {
     lambda.print("Hello");
    }
    public static void main(String[] args) {
        MethodRefObject obj = new MethodRefObject();
        printString(obj::printUpperCase);
    }
}

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

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

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

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

public class Demo05Lambda {
    private static void method(int num, Calcable lambda) {
      System.out.println(lambda.calc(num));
    }
    public static void main(String[] args) {
     method(‐10, n ‐> Math.abs(n));
    }
}

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

public class Demo06MethodRef {
    private static void method(int num, Calcable 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 object is then used to create a function interface:

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

To use this function interface, via Lambda expressions:

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));
    }
}

But by constructing Cite, a better wording:

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);
    }
}

In this example, the following two are equivalent wording:

  • Lambda expressions: name -> new Person(name)
  • Method references: Person::new

2.10 constructor reference to an array

Object arrays are a subclass of object, so having the same configuration is only slightly different syntax. If the corresponding scene using the Lambda, a required interface function:

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

In applying this interface, you can Lambda expressions:

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]);
    }
}

But the wording is better to use an array reference constructor:

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);
    }
}

In this example, the following two are equivalent wording:

  • Lambda expressions: length -> new int[length]
  • Method references: int[]::new

Guess you like

Origin www.cnblogs.com/bruce1993/p/11896528.html