通过Stream将jsonArray转换成list
时间: 2023-11-12 21:06:08 浏览: 101
可以使用Jackson库来实现这个功能。以下是一个示例代码:
```java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JsonToListConverter {
public static void main(String[] args) throws IOException {
String jsonArray = "[{\"name\":\"Alice\",\"age\":20},{\"name\":\"Bob\",\"age\":25},{\"name\":\"Charlie\",\"age\":30}]";
ObjectMapper objectMapper = new ObjectMapper();
List<Person> personList = objectMapper.readValue(jsonArray, new TypeReference<List<Person>>(){});
// 将List转换为Stream
Stream<Person> personStream = personList.stream();
// 按照年龄从小到大排序
List<Person> sortedList = personStream.sorted((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()))
.collect(Collectors.toList());
System.out.println(sortedList);
// Output: [Person{name='Alice', age=20}, Person{name='Bob', age=25}, Person{name='Charlie', age=30}]
}
static class Person {
private String name;
private int age;
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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}
```
在这个示例中,我们首先使用Jackson库将JSON数组转换为List。然后,我们将List转换为Stream,并使用sorted方法按照年龄从小到大排序。最后,我们使用collect方法将Stream转换回List。
阅读全文