New features of java8: Predicate<T> function method usage

The function function method in ava8 is a new feature of jdk1.8. The Predicate<T> method is widely used, and the predicate is an assertion and judgment in English. The Predicate<T> interface is a functional interface, and the test(Object) method that returns a Boolean value of true or false is very useful. Let's take an example to show you the benefits of the Predicate<T> function.

Note: Statements such as "n -> true" in the following methods are Lambda expressions in the new features of java8. The components are parameter -> expression body, the left side of the "->" symbol is the parameter, and the right side is the method body.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class PredicateDemo {
    public static void main(String[] args) {
        //add parameter to list
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        System.out.println("Output all parameter words:");
        eval(list, n -> true);
        System.out.println("\nOutput a number divisible by 2:");
        eval(list, n -> n%2==0);
        System.out.println("\nOutput numbers greater than 3:");
        eval(list, n-> n > 3 );
    }
    
    //custom method
    public static void eval(List<Integer> list, Predicate<Integer> predicate) {
        for(Integer n: list) {        
           if(predicate.test(n)) {
              //You can return the parameters that meet the conditions, only output here
              System.out.print(n + " ");
           }
        }
     }
}

 

The output of the above code is as follows.

Output all parameter words:
1 2 3 4 5 6 7 8 9
Output numbers divisible by 2:
2 4 6 8
Output numbers greater than 3:
4 5 6 7 8 9

 

Everyone knows the benefits of the Predicate<T> functional method in java8. One method can be used in multiple ways!

Reprinted from: http://www.tpyyes.com/a/java/2017/0709/136.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326188498&siteId=291194637