lamda json集合过滤
时间: 2023-07-09 10:54:19 浏览: 112
Lambda表达式可以用来过滤JSON集合。假设你有一个JSON集合,它长这样:
```json
[
{
"name": "Alice",
"age": 25,
"gender": "female"
},
{
"name": "Bob",
"age": 30,
"gender": "male"
},
{
"name": "Charlie",
"age": 20,
"gender": "male"
}
]
```
现在你想过滤这个集合,只留下所有年龄大于等于25岁的人。你可以使用Lambda表达式来实现:
```java
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonFilterExample {
public static void main(String[] args) throws Exception {
String json = "[{\"name\":\"Alice\",\"age\":25,\"gender\":\"female\"},{\"name\":\"Bob\",\"age\":30,\"gender\":\"male\"},{\"name\":\"Charlie\",\"age\":20,\"gender\":\"male\"}]";
ObjectMapper mapper = new ObjectMapper();
List<Person> people = mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, Person.class));
List<Person> filteredPeople = new ArrayList<>();
for (Person person : people) {
if (person.getAge() >= 25) {
filteredPeople.add(person);
}
}
String filteredJson = mapper.writeValueAsString(filteredPeople);
System.out.println(filteredJson);
}
static class Person {
private String name;
private int age;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
}
```
这个例子中,我们首先使用Jackson库将JSON字符串转换为Person对象的List集合。然后,我们使用一个for循环来遍历这个集合,对每个Person对象进行年龄判断,如果年龄大于等于25岁,就将这个Person对象加入到一个新的List集合中。最后,我们将这个新的List集合转换为JSON字符串输出。
输出结果如下:
```json
[{"name":"Alice","age":25,"gender":"female"},{"name":"Bob","age":30,"gender":"male"}]
```
可以看到,只有年龄大于等于25岁的人被保留下来了。
阅读全文