【过滤器案例】:使用Stream对象的filter()方法过滤出集合中Person对象name属性含有”菲”字的对象
创建Person类:
public class Person {
public static enum Sex{
MALE,FEMALE;
}
private String name;
private Sex gender;
private int age;
private double height;
public Person() {
}
public Person(String name, Sex gender, int age, double height) {
super();
this.name = name;
this.gender = gender;
this.age = age;
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Sex getGender() {
return gender;
}
public void setGender(Sex gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public String toString() {
return "Person [name=" + name + ", gender=" + gender + ", age=" + age + ", height=" + height + "]";
}
}
创建测试类,在测试类中创建一个初始化集合的静态方法:
public class Test04_collection_filter {
//初始化集合的静态方法
public static List<Person> createPerson(){
List<Person> people = new ArrayList<Person>();
Person person = new Person("张飞",Person.Sex.MALE,33,1.99);
people.add(person);
person = new Person("王菲",Person.Sex.FEMALE,33,1.65);
people.add(person);
person = new Person("刘亦菲",Person.Sex.FEMALE,33,1.68);
people.add(person);
person = new Person("李四",Person.Sex.MALE,33,1.76);
people.add(person);
person = new Person("小马",Person.Sex.MALE,33,1.71);
people.add(person);
person = new Person("郭靖",Person.Sex.MALE,33,1.88);
people.add(person);
return people;
}
}
在该测试类中,添加main方法,用来测试filter过滤器:
public static void main(String[] args) {
List<Person> people = createPerson();//调用初始化集合的静态方法,初始化一个集合
Stream<Person> stream = people.stream();
stream.filter(p -> p.getName().indexOf("菲")>-1)//过滤器中传入lambda表达式,表达式代码块中书写判断条件,返回一个布尔值
.forEach(p -> {
System.out.println(p);
});//紧接着调用forEach方法,遍历集合,打印集合中每个对象
}
运行main方法,控制台打印结果如下:
Person [name=王菲, gender=FEMALE, age=33, height=1.65]
Person [name=刘亦菲, gender=FEMALE, age=33, height=1.68]
本文代码资源地址: