Predicate 一个函数式接口,属于java.util.function包,主要用来对输入的对象按照指定的条件进行过滤。
通过以下代码来看看如何使用该类:
package concurrent;
import entry.People;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Created by LHL on 2016/12/16.
*/
public class PredicateDemo {
//男的
public static Predicate isMale(){
return p->"man".equals(p.getSex());
}
//年龄大于age
public static Predicate ageMoreThan(int age){
return people -> people.getAge()>age;
}
//女的并且年龄小于age
public static Predicate isFemalAndAgeLessThan(int age){
return people -> "woman".equals(people.getSex())&&people.getAge() filterPeople(List peopleList,Predicate peoplePredicate){
return peopleList.stream().filter(peoplePredicate).collect(Collectors.toList());
}
public static void main(String[] args) {
People xiaoMing = new People("小明",25,"man");
People xiaoHong = new People("小红",38,"woman");
People xiaoFang = new People("小芳",19,"woman");
People xiaoLiu = new People("小刘",29,"man");
People xiaoHei = new People("小黑",56,"man");
List peopleList = Arrays.asList(new People[]{xiaoMing,xiaoHong,xiaoFang,xiaoLiu,xiaoHei});
//男的
System.out.println(PredicateDemo.filterPeople(peopleList,PredicateDemo.isMale()));
//年龄大于50的
System.out.println(PredicateDemo.filterPeople(peopleList,PredicateDemo.ageMoreThan(50)));
//女的的并且年龄小于20的
System.out.println(PredicateDemo.filterPeople(peopleList,isFemalAndAgeLessThan(20)));
//逆条件 及与条件不符
System.out.println(PredicateDemo.filterPeople(peopleList,isFemalAndAgeLessThan(20).negate()));
}
}
看看程序的运行结果:
[People{name='小明', age=25, sex='man'}, People{name='小刘', age=29, sex='man'}, People{name='小黑', age=56, sex='man'}]
[People{name='小黑', age=56, sex='man'}]
[People{name='小芳', age=19, sex='woman'}]
[People{name='小明', age=25, sex='man'}, People{name='小红', age=38, sex='woman'}, People{name='小刘', age=29, sex='man'}, People{name='小黑', age=56, sex='man'}]
是不是比你遍历集合要方便的多,这就是函数式编程的所带来的好处。
附:People类
package entry;
/**
* Created by LHL on 2016/12/16.
*/
public class People {
private String name;
private int age;
private String sex;
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public People(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
}