java 集合怎么根据 字段过滤
时间: 2024-05-01 19:24:03 浏览: 78
Java集合中可以使用Stream API来根据字段进行过滤。具体步骤如下:
1.将集合转换成Stream流。
2.使用filter()方法对流进行过滤,其中lambda表达式中编写过滤条件。
3.使用collect()方法将过滤后的元素收集起来,可以使用toList()方法将结果转换为List集合。
下面是一个根据字段过滤List集合中对象的示例代码:
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Tom", 20));
personList.add(new Person("Jack", 25));
personList.add(new Person("Lucy", 30));
personList.add(new Person("Mike", 18));
List<Person> filteredList = personList.stream()
.filter(p -> p.getAge() > 20) // 过滤出年龄大于20岁的Person对象
.collect(Collectors.toList());
filteredList.forEach(p -> System.out.println(p.getName()));
}
}
```
输出结果为:
```
Jack
Lucy
```
可以看到,经过过滤后,只有年龄大于20岁的Person对象被收集到了List集合中。
阅读全文
相关推荐

















