1、代码
(1)
package com.example.demo12;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
public class Test15 {
public static void main(String[] args) {
List<User> list=new ArrayList<>();
User user1=new User("a",17);
User user2=new User("b",15);
User user3=new User("c",16);
list.add(user1);
list.add(user2);
list.add(user3);
Predicate<User> predicate1= user -> {
if (user.getStudentAge()>16){
return true;
}else
return false;
};
Predicate<User> predicate2=user -> {
if (user.getStudentName()=="a"){
return true;
}else
return false;
};
Predicate<User> predicate3 = Predicates.and(predicate1,predicate2);
List<User> list1=Lists.newArrayList(Iterables.filter(list,predicate3));
list1.stream().forEach(l->{
System.out.println(l.toString());
});
}
}
(2)
package com.example.demo12;
public class User {
private String studentName;
private int studentAge;
public User() {
}
public User(String studentName, int studentAge) {
this.studentName = studentName;
this.studentAge = studentAge;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
@Override
public String toString() {
return "User{" +
"studentName='" + studentName + '\'' +
", studentAge=" + studentAge +
'}';
}
}
2、结果
User{studentName='a', studentAge=17}
3、解释
(1)此Predicate类不同于Java8的Predicate类,大家引入包的时候不要错了,否则是应用不了Guava的方法的;
(2)我们先准备好一个list,然后定义好list的Predicate条件,这里我们可以定义多个过滤条件,调用Guava的Predicates的and方法(不同于Java8的and方法),可以把多个过滤条件合并起来, 利用Guava的Lists来调用。