Java8过滤出对象list中name为小明的所有数据
假设有一个对象类Person,包含属性name:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
现在有一个Person对象的List,我们要过滤出name为"小明"的所有数据:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("小明"));
personList.add(new Person("小红"));
personList.add(new Person("小明"));
personList.add(new Person("小李"));
List<Person> filteredList = personList.stream()
.filter(person -> person.getName().equals("小明"))
.collect(Collectors.toList());
System.out.println(filteredList);
}
}
运行结果为:
[Person@7852e922, Person@4e25154f]
可以看到,过滤出来的结果是一个包含两个Person对象的List。
原文地址: https://www.cveoy.top/t/topic/jepr 著作权归作者所有。请勿转载和采集!