Hello, classmate. Here is a copy of your unread code, waiting for you to check.
This article belongs to Java 8 tutorial (LTS) Series of tutorials, click to read more related articles.
The predict function interface is the same as that described earlier Function Like interface, it is a functional interface, which can accept a generic < T > parameter, and the return value is Boolean. Predicate is often used for data filtering, such as filtering out elements that meet a certain condition in a collection.
Source code: function interface predict in Java 8.
package java.util.function; import java.util.Objects; @FunctionalInterface public interface Predicate<T> { boolean test(T t); default Predicate<T> and(Predicate<? super T> other) { Objects.requireNonNull(other); return (t) -> test(t) && other.test(t); } default Predicate<T> negate() { return (t) -> !test(t); } default Predicate<T> or(Predicate<? super T> other) { Objects.requireNonNull(other); return (t) -> test(t) || other.test(t); } static <T> Predicate<T> isEqual(Object targetRef) { return (null == targetRef) ? Objects::isNull : object -> targetRef.equals(object); } }
1. Predicate test
The predict function interface can be used to judge whether a parameter meets a certain condition.
Example: judge whether a string is empty.
import java.util.function.Predicate; public class Java8PredicateTest { public static void main(String[] args) { Predicate<String> isEmpty = String::isEmpty; System.out.println(isEmpty.test("")); System.out.println(isEmpty.test("www.wdbyte.com")); } }
Output results:
true false
2. Predicate Stream filter
The filter() method in Stream is implemented by receiving a Predicate function interface.
Example: filter out strings with string length of 4 in the collection.
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Java8PredicateFilter { public static void main(String[] args) { List<String> list = Arrays.asList("java", "node", "www.wdbyte.com"); list = list.stream().filter(str -> str.length() == 4).collect(Collectors.toList()); System.out.println(list); } }
Output results:
[java, node]
3. Predicate and
Using the and() method, you can make the two Predicate judgment conditions take effect together.
Example 1: filter numbers in the number set with a number size between 5 and 9.
import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class Java8PredicateAnd { public static void main(String[] args) { List<Integer> numberList = Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10); Predicate<Integer> greaterThan5 = number -> number > 5; Predicate<Integer> lessThan9 = number -> number < 9; Predicate<Integer> filter = greaterThan5.and(lessThan9); numberList = numberList.stream().filter(filter).collect(Collectors.toList()); System.out.println(numberList); } }
Result output:
[6, 7, 8]
Example 2: a Predicate filters numbers in a number set with a number size between 5 and 9.
List<Integer> numberList = Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10); numberList = numberList.stream().filter(x -> x > 5 && x < 9).collect(Collectors.toList()); System.out.println(numberList);
Output results;
[6, 7, 8]
4. Predicate negate
Predicate. The negative () method will return a Predicate that is contrary to the specified judgment.
Example: filter the number in the number set whose number is not greater than 5.
import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class Java8PredicateNeagete { public static void main(String[] args) { List<Integer> numberList = Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10); Predicate<Integer> greaterThan5 = number -> number > 5; numberList = numberList.stream().filter(greaterThan5.negate()).collect(Collectors.toList()); System.out.println(numberList); } }
Output results:
[3, 4, 5]
5. Predicate or
Example: filter numbers less than or equal to 5 or greater than or equal to 9 in the number set.
import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class Java8PredicateOr { public static void main(String[] args) { List<Integer> numberList = Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10); Predicate<Integer> lessThan5 = number -> number <= 5; Predicate<Integer> greaterThan8 = number -> number >= 9; numberList = numberList.stream().filter(lessThan5.or(greaterThan8)).collect(Collectors.toList()); System.out.println(numberList); } }
Output results:
[3, 4, 5, 9, 10]
6. Predict chain programming
The or(), and(), and negative() methods of predict can combine predict at will. The judgment logic after combination is from left to right and from front to back.
For example: (the number is less than 5). and (the number is greater than 9). negate ().
Solution: (the number is less than 5) AND (the number is greater than 9) get false for any number, AND false. Negative () get the opposite true.
Therefore, this judgment logic is true for any number.
Example: predict's or(), and(), and negate() methods are used in combination.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class Java8PredicateChain { public static void main(String[] args) { List<Integer> numberList = Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10); Predicate<Integer> lessThan5 = number -> number <= 5; Predicate<Integer> greaterThan9 = number -> number >= 9; // Up to 5 System.out.println(filter(numberList, lessThan5)); // Greater than 5 System.out.println(filter(numberList, lessThan5.negate())); // Less than or equal to 5 or greater than or equal to 9 System.out.println(filter(numberList, lessThan5.or(greaterThan9))); // ! (less than or equal to 5 AND greater than or equal to 9) System.out.println(filter(numberList, lessThan5.and(greaterThan9).negate())); } public static <T> List<T> filter(List<T> list, Predicate<T> predicate) { List<T> resultList = new ArrayList<>(); for (T t : list) { if (predicate.test(t)) { resultList.add(t); } } return resultList; } }
Output results:
[3, 4, 5] [6, 7, 8, 9, 10] [3, 4, 5, 9, 10] [3, 4, 5, 6, 7, 8, 9, 10]
7. Predicate and object
Example: filter dogs that meet certain characteristics.
import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class Java8PredicateObject { public static void main(String[] args) { List<Dog> dogList = new ArrayList<>(); dogList.add(new Dog("Siberian Husky", 1)); dogList.add(new Dog("Shepherd Dog", 2)); dogList.add(new Dog("Koki", 3)); dogList.add(new Dog("Shiba Inu", 3)); // Find a 3-year-old dog System.out.println(filter(dogList, dog -> dog.getAge().equals(3))); // Find husky information Predicate<Dog> predicate = dog -> ("Siberian Husky").equals(dog.getName()); System.out.println(filter(dogList, predicate)); } public static <T> List<T> filter(List<T> list, Predicate<T> predicate) { List<T> resultList = new ArrayList<>(); for (T t : list) { if (predicate.test(t)) { resultList.add(t); } } return resultList; } } class Dog { private String name; private Integer age; public Dog(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Dog{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
Output results:
[Dog{name='Koki', age=3}, Dog{name='Shiba Inu', age=3}] [Dog{name='Siberian Husky', age=1}]
Like the Predicate function interface, BiPredicate returns a boolean type. The only difference is that Predicate accepts one parameter, while BiPredicate can accept two different types of parameters.
BiPredicate source code in Java 8:
package java.util.function; import java.util.Objects; @FunctionalInterface public interface BiPredicate<T, U> { boolean test(T t, U u); default BiPredicate<T, U> and(BiPredicate<? super T, ? super U> other) { Objects.requireNonNull(other); return (T t, U u) -> test(t, u) && other.test(t, u); } default BiPredicate<T, U> negate() { return (T t, U u) -> !test(t, u); } default BiPredicate<T, U> or(BiPredicate<? super T, ? super U> other) { Objects.requireNonNull(other); return (T t, U u) -> test(t, u) || other.test(t, u); } }
Extended reading
Java 8 Function function interface
Java 8 Predicate function interface
Java 8 Consumer function interface
Java 8 Supplier function interface
Java 8 BiFunction function interface
Java 8 BiPredicate function interface
Java 8 UnaryOperator function interface
reference resources
BiPredicate (Java Platform SE 8 )
Predicate (Java Platform SE 8 )
Java 8 Predicate function interface
That's all for this article. I'm a tossing program ape who wants to write articles seriously.
If you want to subscribe, you can follow The official account is "unread code". , or Unread code blog , or Add wechat (wn8398).
This article has also been sorted to GitHub.com/niumoo/JavaNotes Welcome, Star.
