对对象集合进行处理时,整天for循环筛选,感觉跟不上时代。搜了搜,学了学java8的Stream,并用来替代for循环筛选。
public class StreamTest {
public static void main (String[] args) {
List<Person> persons = Arrays.asList(
new Person("e1", "l1"),
new Person("e2", "l1"),
new Person("e3", "l2"),
new Person("e4", "l2"),
new Person("e5", "l3"),
new Person("e6", "l3"),
new Person("e7", "l3")
);
//.filter(过滤条件)
//.collect(Collectors.toList()) 把结果搜集到List之中。
persons = persons.stream().filter(person -> person.getLastName().equals("l3")).collect(Collectors.toList());
persons.forEach(person -> {
System.out.println(person.getName());
});
}
}
public class Person {
private String name;
private String lastName;
public Person(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
结果:
e5
e6
e7