Java—Java 8 new features explained (Predicate and Stream)

Predicate interface

Introduction to Predicate interface

  Predicate is a functional interface that can use Lambda expressions as parameters. Java 8 adds a new removeIf(Predicate filter)method to the Collection , which can delete all elements that meet the filter conditions in batches.

Predicate interface usage examples

Test Collection removeIf()methods.
Example 1
1) Run class:

public class DemoApplication {

    public static void main(String[] args) {

        // 创建集合
        Collection collection = new HashSet();

        // 添加元素
        collection.add("book01");
        collection.add("book02");
        collection.add("book03");
        collection.add("b05");
        collection.add("b06");

        Collection collectionNew = new HashSet();
        // 使用Lambda表达式遍历传入新的集合
        collection.forEach(str -> collectionNew.add(str));
        System.out.println("collectionNew: " + collectionNew);

        // 使用Lambda表达式进行过滤(目标类型是Predicate)
        collection.removeIf(filter -> ((String)filter).length() < 5);

        // 使用Lambda表达式遍历打印
        collection.forEach(str -> System.out.println(str));

        
        }
}

2) Operation result:

collectionNew: [book02, book01, b05, book03, b06]
book02
book01
book03

  From the above results, we can see a call Collection collection removeIf()methods, batch filter can meet the conditions of the collection element length is less than 5, the program is a Lambda expression to filter incoming: collection.removeIf(filter -> ((String)filter).length() < 5);.

Example 2 Method
using Predicate interface 1) Create a tool class:boolean test(T t);

import java.util.Collection;
import java.util.function.Predicate;

/**
 * @author andya
 * @create 2020-03-24 14:08
 */
public class PredicateUtil {
    public static int countCollectionElement(Collection collection, Predicate predicate){
        int total = 0;
        for (Object object : collection) {
            //通过Predicate的test()方法判断对象是否满足过滤条件
            if (predicate.test(object)) {
                total ++;
            }
        }

        return total;
    }
}

2) Run class:

public class DemoApplication {

    public static void main(String[] args) {

        // 创建集合
        Collection collection = new HashSet();

        // 添加元素
        collection.add("book_java编程思想");
        collection.add("book_c++核心技术");
        collection.add("book_java核心技术");
        collection.add("book_计算机网络");
        collection.add("book01");
        collection.add("book02");

        Collection collectionNew = new HashSet();
        // 使用Lambda表达式遍历传入新的集合
        collection.forEach(str -> collectionNew.add(str));
        System.out.println("collectionNew: " + collectionNew);

        System.out.println("包含java关键字的个数:" +
                PredicateUtil.countCollectionElement(collection, ele -> ((String)ele).contains("java")));
        System.out.println("长度小于7的个数:" +
                PredicateUtil.countCollectionElement(collection, ele -> ((String)ele).length() < 7));
        System.out.println("以book_为前缀的个数:" +
                PredicateUtil.countCollectionElement(collection, ele -> ((String)ele).startsWith("book_")));
        }
}

3) Operation result:

collectionNew: [book02, book01, book_java编程思想, book_java核心技术, book_计算机网络, book_c++核心技术]
包含java关键字的个数:2
长度小于7的个数:2
以book_为前缀的个数:4

  A countCollectionElement()method is defined that uses Predicate to dynamically pass parameters to determine whether each collection element meets the filtering conditions.

Stream interface

Stream stream interface introduction

  Java 8 new features also added streaming, such as Stream, IntStream, DoubleStream, LongStream and other APIs. Each streaming API also provides corresponding Builder, such as Stream.Builder, IntStream.Builder, DoubleStream.Builder, LongStream.Builder.

Stream usage steps

  1. Use Stream and other API builder()class methods to create the corresponding Builder class of Stream;
  2. Call the Builder add()method to add multiple elements to the stream;
  3. Call the build()method of Builder to get the corresponding Stream;
  4. Call the Stream aggregation method;

Stream usage example

public class DemoApplication {

    public static void main(String[] args) {

        //通过xxxStream的builder()方法去创建Builder
        IntStream intStream = IntStream.builder()
                .add(1)
                .add(-2)
                .add(3)
                .add(10)
                .build();

        // 聚集方法(每次只能使用其中一条去执行,其他代码需注释,否则会报错)
        System.out.println("intStream的元素最大值是: " + intStream.max().getAsInt());
        System.out.println("intStream的元素最小值是: " + intStream.min().getAsInt());
        System.out.println("intStream的元素平均值是: " + intStream.average());
        System.out.println("intStream的元素总和是: " + intStream.sum());
        System.out.println("intStream的元素个数是: " + intStream.count());
        System.out.println("intStream是否包含任何元素平方大于10: "
                + intStream.anyMatch(ele -> ele * ele > 10));
        System.out.println("intStream的所有元素立方是否大于10: "
                + intStream.allMatch(ele -> ele * ele * ele > 10));

        // 每个元素都加1后映射成新的Stream
        IntStream intStreamNew = intStream.map(ele -> ele + 1);
        intStreamNew.forEach(ele -> System.out.println(ele));
        }
}

Operation result: put all the execution results of the above aggregation method into one display, in fact, only one can be executed;

intStream的元素最大值是: 10
intStream的元素最小值是: -2
intStream的元素平均值是: OptionalDouble[3.0]
intStream的元素总和是: 12
intStream的元素个数是: 4
intStream是否包含任何元素平方大于10true
intStream的所有元素立方是否大于10: false
2
-1
4
11

In the above example, there are two aggregation methods: "intermediate method" and "end method".

  • Intermediate methods : Intermediate operations allow the stream to remain open and allow subsequent methods to be called directly, such as map()methods with a return value of another stream;
  • End method : The end method is the final operation sum()performed on the stream . If the method is executed, the stream is unavailable. If it is used again, an error will be reportedException in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed

Common methods of Stream

Intermediate method

  • filter(Predicate predicate): Filters elements in the Stream that do not meet the predicate filtering conditions.
  • mapToXxx(ToXxxFunction mapper): Use ToXxxFunction to perform a one-to-one conversion on the elements in the stream. The method returns all the elements generated by the ToXxxFunction transformation in the new stream.
  • peek(Consumer action): Operate each element in turn. The returned stream contains the same elements as the original stream and is used for debugging.
  • distinct(): Stateful method for sorting all repeated elements in the stream;
  • sorted(): It is used to ensure that the elements in the stream are in an ordered state during subsequent visits, and it is also a stateful method.
  • limit(long maxSize): It is used to ensure the maximum number of elements that can be accessed in subsequent accesses to the stream. It is a stateful, short-circuit method.

End method

  • forEach(Consumer action): Traverse all elements in the stream and execute action.
  • toArray(): Convert all elements in the stream into an array.
  • reduce(): Used to merge elements in an operation.
  • min(): Returns the minimum value of elements in the stream.
  • max(): Returns the maximum value of elements in the stream.
  • sum(): Returns the sum of the elements in the stream.
  • count(): Returns the number of all elements in the stream.
  • anyMatch(Predicate predicate): Determine whether the stream contains at least one element that meets the predicate filter condition.
  • allMatch(Predicate predicate): Determine whether all elements in the stream meet the predicate filter condition.
  • noneMatch(Predicate predicate): Determine whether all elements in the stream do not meet the predicate filter condition.
  • findFirst(): Returns the first element in the stream.
  • findAny(): Return any element in the stream.

The stream () method in Collection

public class DemoApplication {

    public static void main(String[] args) {
   		// 创建集合
        Collection collection = new HashSet();

        // 添加元素
        collection.add("book_java编程思想");
        collection.add("book_c++核心技术");
        collection.add("book_java核心技术");
        collection.add("book_计算机网络");
        collection.add("book01");
        collection.add("book02");
        collection.forEach(ele -> System.out.println(ele));

        System.out.println("-------------------------------------");

        System.out.println("包含java关键字的个数:"
                + collection.stream().filter(ele -> ((String)ele).contains("java")).count());
        System.out.println("长度小于7的个数:"
                + collection.stream().filter(ele -> ((String)ele).length() < 7).count());
        System.out.println("以book_为前缀的个数:"
                + collection.stream().filter(ele -> ((String)ele).startsWith("book_")).count());

        System.out.println("-------------------------------------");

        //先调用Collection的stream()方法将集合转化为Stream;
        //再调用Stream的mapToInt()方法获取Stream对象的IntStream对象;
        //最后调用forEach()方法遍历IntStream中的元素。
        Collection collectionLength = new ArrayList();
        collection.stream().mapToInt(ele -> ((String)ele).length())
                .forEach(ele -> ((ArrayList) collectionLength).add(ele));
        //等价于collectionLength.forEach(ele -> System.out.println(ele));
        collectionLength.forEach(System.out::println);
        }
}

operation result

book02
book01
book_java编程思想
book_java核心技术
book_计算机网络
book_c++核心技术
-------------------------------------
包含java关键字的个数:2
长度小于7的个数:2
以book_为前缀的个数:4
-------------------------------------
6
6
13
13
10
12

  In collection.stream().filter(Predicate<? super T> predicate).count()this way, you can replace the PredicateUtil method created earlier in the article.
stream()Methods as below:

    default Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }

filter()Methods as below:

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

  In addition to directly using the Stream stream interface to process the elements of the Collection collection, we can also stream()return the stream corresponding to the collection through the method of the Collection interface .
Proceed as follows:

  1. First call the stream()method of Collection to convert the collection to Stream;
  2. Then call the Stream mapToInt()method to obtain the IntStream object of the Stream object;
  3. Finally call the forEach()method to traverse the elements in IntStream.

Reference book "Crazy Java"

Published 118 original articles · Like 150 · Visits 40,000+

Guess you like

Origin blog.csdn.net/Andya_net/article/details/105064799