本文介绍了如何通过流java8中的键获取所有不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在学习一些有关流的知识.我具有以下JSONArray,并且希望能够检索所有不同的xvalue.
I am currently learning a bit about streams.I have the following JSONArray, and I want to be able to retrieve all the distinct xvalues.
datasets: {
ds1: {
xvalues: [
"(empty)",
"x1",
"x2"
]
},
ds2: {
xvalues: [
"(empty)",
"x1",
"x2",
"x3"
]
}
}
我正在尝试以下代码,但似乎不太正确....
I am trying the following code but it doesn't seem quite right....
List<String> xvalues = arrayToStream(datasets)
.map(JSONObject.class::cast)
.map(dataset -> {
try {
return dataset.getJSONArray("xvalues");
} catch (JSONException ex) {
}
return;
})
.distinct()
.collect((Collectors.toList()));
private static Stream<Object> arrayToStream(JSONArray array) {
return StreamSupport.stream(array.spliterator(), false);
}
推荐答案
我相信使用json库(Jackson,Gson)是处理json数据的最佳方法.如果可以使用Jackson,这可能是一个解决方案
I believe using a json library(Jackson, Gson) is the best way to deal with json data. If you can use Jackson, this could be a solution
public class DataSetsWrapper {
private Map<String, XValue> datasets;
//Getters, Setters
}
public class XValue {
private List<String> xvalues;
//Getters, Setters
}
ObjectMapper objectMapper = new ObjectMapper();
DataSetsWrapper dataSetsWrapper = objectMapper.readValue(jsonString, DataSetsWrapper.class);
List<String> distinctXValues = dataSetsWrapper.getDatasets()
.values()
.stream()
.map(XValue::getXvalues)
.flatMap(Collection::stream)
.distinct()
.collect(Collectors.toList());
将jsonString替换为您的json.我用json
Replace jsonString with your json. I tested this with this json
String jsonString = "{\"datasets\": {\n" +
" \"ds1\": {\n" +
" \"xvalues\": [\n" +
" \"(empty)\",\n" +
" \"x1\",\n" +
" \"x2\"\n" +
" ]\n" +
" },\n" +
" \"ds2\": {\n" +
" \"xvalues\": [\n" +
" \"(empty)\",\n" +
" \"x1\",\n" +
" \"x2\",\n" +
" \"x3\"\n" +
" ]\n" +
" }\n" +
"}}";
这篇关于如何通过流java8中的键获取所有不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!