[Java] - Predicate Interface
Friday, April 27, 2018
Predicate Interface is a functional interface that represents a predicate of one
argument and it is defined in java.util.function packages. That helps your code
is simple.
Ref:
-
https://docs.oracle.com/javase/8/docs/api/java/util/function/class-use/Predicate.html
- http://www.java2s.com/Tutorials/Java/java.util.function/Predicate/index.htm
1. Predicate example 1
Predicate<Integer> pr = b
-> (b >= 18); // Creating predicate
System.out.println(pr.test(18));
// Calling Predicate method
Results:
true
Results:
true
2. Predicate example 2
(Lambda and Method Reference)
Student.java
package com.javacore.stream;
public class Student {
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "name = " + this.name +
";age= " + this.age;
}
}
Main.java
package com.javacore.stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import
java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
// create some student
Student andy = new Student("andy",
25);
Student susi = new Student("susi",
26);
Student tom = new Student("tom",
24);
Student adam = new Student("adam",
25);
// create student list
List<Student> studentList =
Arrays.asList(andy, susi, tom, adam);
//use Method Reference
List<Student> studentOf25Age =
filter(studentList, Main::isStudentAgeLessThan);
System.out.println(studentOf25Age);
//use lambda
List<Student> studentOf26Age =
filter(studentList, (Student student) -> 26 == student.getAge());
System.out.println(studentOf26Age);
}
public static boolean isStudentAgeLessThan(Student argStudent) {
if (argStudent.getAge() < 25) {
return true;
}
return false;
}
public static List<Student> filter(List<Student> argStudentList,
Predicate<Student> argPredicate) {
List<Student> studentList = new
ArrayList<>();
for (Student student : argStudentList) {
if (argPredicate.test(student)) {
studentList.add(student);
}
}
return studentList;
}
}
Results:
[name = tom;age= 24]
[name = susi;age= 26]
updating...
Bài liên quan
Comments[ 0 ]
Post a Comment