1. Stream introduction

Stream streams are used to simplify collections and arrays. In Java8, thanks to the functional programming enabled by Lambda, a whole new Stream concept was introduced, converting collections and arrays into streams and using methods in Stream streams.

2. Initial experience of Stream programming

public class Demo15Stream { public static void main(String[] args) { List<String> list = new ArrayList<String>(); List. The add (" zhang "); List.add (" list "); List. The add (" zhao "); List.add (" zhang Xiaohua "); Filter (s -> s.length()==3) // print one by one. ForEach (s -> s.length()==3) System.out.println(s)); }}Copy the code

3. Overview of streaming ideas

A Stream is a queue of elements from a data source. A Stream does not store elements, but evaluates on demand. The source of a data Stream can be a collection or array.

4. Get the stream

There are several ways to get streams:

  1. All collections can get streams through the stream default method.
  2. The static method of the Stream interface gets the corresponding Stream of the array.

4.1 Obtaining streams by Collection

public static void test(){
    List<String> list =  new ArrayList<>();
    Stream<String> stream = list.stream();
    Set<String> set = new HashSet<>();
    Stream<String> stream1 = set.stream();
}
Copy the code

4.2. Get streams according to Map

public static void testMap(){
    Map<String, String> map = new HashMap<>();
    Stream<String> stream = map.keySet().stream();
    Stream<String> stream1 = map.values().stream();
    Stream<Map.Entry<String, String>> stream2 = map.entrySet().stream();
}
Copy the code

4.3. Get streams from arrays

Public static void testArr(){String[] arr = {}; public static void testArr(){String[] arr = {}; Stream<String> arr1 = Stream.of(arr); }Copy the code

5. Common methods

  • Delayed methods: The return value type is still a method of the Stream interface’s own type, so chained calls are supported.
  • Finalizing methods: Methods whose return type is no longer of the Stream interface’s own type. Finalizing methods include count and forEach.

5.1 Processing one by one: foreach

This method receives a Consumer interface function that hands each stream element to the function for processing.

@test public void testForEach(){Stream<String> Stream = stream.of (" 三", "三"," 三"); stream.forEach(s->System.out.println(s)); }Copy the code

5.2. Filter: filter

A stream can be converted to a subset stream using the Filter method, which takes a Predicate function as an interface.

@test public void testFilter(){Stream<String> Stream = stream.of (" 三", "三"," 三"); Stream.filter (s -> s.tartswith (" ")).foreach (s -> system.out.println (s)); }Copy the code

5.3. Mapping: Map

If you need to map elements in a flow to another flow, you can use the Map method, which takes a Function functional interface as an argument and converts the T type in the current flow to another R type.

@Test
public void testMap(){
    Stream<String> stringStream = Stream.of("11", "22", "9");
    Stream<Integer> result = stringStream.map((s -> Integer.parseInt(s)));
    result.forEach(s->System.out.println(s));
    
}
Copy the code

5.4. Number of statistics: count

Use the count method to count the number of elements in the stream.

@test public void testCount(){Stream<String> Stream = stream.of (" 下 载 ", "下 载 "," 下 载 "); System.out.println(stream.filter(s -> s.tartswith (" ")).count()); }Copy the code

5.5. Use the first few: limit

Limit can be truncated by taking the first few arguments of type long. If the current length of the set is greater than the arguments, truncation is performed. Otherwise, no operation is performed.

@test public void testLimit(){Stream<String> Stream = stream.of (" 大 连 ", "大 连 "," 大 连 ", "大 连 "); stream.limit(3).forEach(s->System.out.println(s)); }Copy the code

5.6 Skip the first few: skip

If you want to skip the first few elements, you can use the Skip method to get a new truncated stream. The argument is of type long. If the current length of the stream is greater than n, the first n will be skipped. Otherwise, an empty stream of length 0 will be obtained.

@test public void testSkip(){Stream<String> Stream = stream.of (" 微 实 ", "微 实 "," 微 实 "); stream.skip(2).forEach(s-> System.out.println(s)); }Copy the code

5.7 Combination: concat

If you have two streams that you want to merge into one, you can use concat, the static method of the Stream interface.

@test public void testConcat(){Stream<String> streamZ = stream.of (" 三"); Stream<String> streamL = stream.of (" "); Stream<String> streamL = stream.of (" "); Stream<String> concatStream = Stream.concat(streamZ, streamL); concatStream.forEach(s-> System.out.println(s)); }Copy the code

6. Method references

6.1. Method references

The double colon :: is the reference operator, and the expression in which the lambda is expressed is called a method reference. If the function scheme that lambda is expressing already exists in a method implementation, the method can be referred to as a lambda substitute by the double colon.

6.2. Reference member methods by object names

A member method already exists in a class

public class MethodRefObject { public void printUpperCaseString(String s){ System.out.println(s.toUpperCase()); }}Copy the code

Functional interface definitions:

@FunctionalInterface
public interface Printable {
    public abstract void print(String s);
}
Copy the code

When you want to use the printUpperCase method, you already have an instance of the MethodRefObject class, so you can refer to the member method by object name.

public class Demo01Functional { public static void printString(Printable p){ p.print("hello"); } public static void main(String[] args) { MethodRefObject methodRefObject = new MethodRefObject(); printString(methodRefObject::printUpperCaseString); }}Copy the code

6.3. Reference static methods by class name

Functional interface:

@FunctionalInterface
public interface Calcable {
    int calsAbs(int number);
}
Copy the code

Class names refer to static methods

public class Demo02Functional { public static int method(int num, Calcable c) { return c.calsAbs(num); } public static void main(String[] args) {public static void main(String[] args) {public static void main(String[] args) { Math::abs); System.out.println(absNum); }}Copy the code

6.4 Referencing member methods through super

If inheritance exists, method references can be used instead when a super call is needed in a lambda expression. Functional interface:

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

The parent class Human:

Public class Human {public void sayHello(){system.out.println (" Hello, I am Human"); }}Copy the code

Subclass Man, using super to reference member methods:

Public class Man extends Human{@override public void sayHello() {system.out.println (" Hello, I am Man"); } public void method(Greetable greetable){ greetable.greet(); } public void show(){ method(super::sayHello); } public static void main(String[] args){ new Man().show(); }}Copy the code

6.5 Reference member methods through this

This represents the current object. If the method you want to reference is a member method of the current class, you can use the format of this:: member method to use method references. Functional interface

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

Define a Husband class:

Public class Husband {private void buyHouse(){system.out.println (" buy a house "); } public void marry(Richable richable){ richable.buy(); } public void beHappy(){ marry(this::buyHouse); } public static void main(String[] args) { new Husband().beHappy(); }}Copy the code

6.6 Class constructor references

Since the constructor name is exactly the same as the class name, the constructor reference can be expressed in the form of the class name ::new. Define a Person class.

public class Person { private String name; public Person(String name){ this.name = name; } @Override public String toString() { return "Person{" + "name='" + name + ''' + '}'; }}Copy the code

Create a functional interface:

@FunctionalInterface
public interface PersonBuilder {
    Person builderPerson(String name);
}
Copy the code
public class Demo04Functional { public static void printName(String name, PersonBuilder personBuilder){ Person person = personBuilder.builderPerson(name); System.out.println(person); } public static void main(String[] args) {// constructor new Person(String name) PrintName (" Person ", Person::new); }}Copy the code

6.7 Array constructor reference

Arrays are subclasses of Object, so they also have constructors, albeit with slightly different syntax. Define a functional interface:

@FunctionalInterface
public interface ArrayBuilder {
    int[] builderArray(int size);
}
Copy the code
public class Demo05Functional { public static int[] createArray(int size, ArrayBuilder arrayBuilder){ return arrayBuilder.builderArray(size); } public static void main(String[] args){public static void main(String[] args){public static void main(String[] args){public static void main(String[] args) Int [] array = createArray(5, int[]::new); System.out.println(Arrays.toString(array)); }}Copy the code