[英]How to filter the list based on the value of a key from JsonArray
How can I filter a list based on the values of the JSONArray
? 如何根据
JSONArray
的值过滤列表?
JSONArray
has the elements which is in simple json structure with key and values. JSONArray
具有简单的带有键和值的json结构的元素。
JSONArray
is from the package org.json
and using this dependency JSONArray
来自包org.json
并使用此依赖项
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
The string response I get when I hit an endpoint is parsed in this way 命中端点时得到的字符串响应将以这种方式解析
String response = [{"ID": 1,"updatedAt": "2019-04-12T09:09:48"},{"ID": 2,"updatedAt": "2019-04-12T09:09:48"}
JSONArray jsonArray = new JSONArray(response)
The list I want to filter consists of list of json strings List<String> eventDataSetList
我要过滤的列表由json字符串
List<String> eventDataSetList
Now how can I filter the list using the value of key ID
from jsonArray
in a better way than this? 现在,我该如何使用比
jsonArray
中的键ID
值更好的方法来过滤列表?
Here is what I have done so far, But I really don't want to use nested loop: 这是我到目前为止所做的,但是我真的不想使用嵌套循环:
Map<Object, String> filteredEvents = new HashMap<>();
for (String event : eventDataSetList) {
for (Object obj : jsonArray) {
JSONObject jsonObject = (JSONObject) obj;
if (event.contains(jsonObject.getString("ID"))) {
filteredEvents.put(jsonObject, event);
}
}
}
You can use Java Stream API with this: 您可以通过以下方式使用Java Stream API:
Map<JSONObject, String> filteredEvents = StreamSupport.stream(jsonArray.spliterator(), false).map(o -> (JSONObject) o)
.flatMap(o -> eventDataSetList.stream().filter(e -> e.contains(o.getString("ID"))).map(e -> new AbstractMap.SimpleEntry<>(o, e)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
This creates a Stream, which iterates over all elements in your JSON array and finds all events matching the condition event.contains(jsonObject.getString("ID"))
. 这将创建一个Stream,该Stream遍历JSON数组中的所有元素,并找到与条件
event.contains(jsonObject.getString("ID"))
匹配的所有事件。 Finally they are collected to a Map. 最后,将它们收集到地图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.