假设我有一个 JSON 对象的 JSON 数组(在 JSON 对象内部)。
{
data:
[
{id:45, building:1, lane: 6},
{id:58, building:1, lane: 9},
{id:46, building:2, lane: 4},
{id:51, building:2, lane: 9},
{id:40, building:3, lane: 2},
{id:39, building:4, lane: 3}
]
}
我想循环遍历数组并将每个 JSON 对象添加到新的 JSON 数组中,但前提是某个键 (building
) 的值之一尚未添加到新的 JSON 数组。
例如,如果我迭代 JSON 数组并到达 id:45
,我想将该对象添加到我的新 JSON 数组中,但前提是尚不存在具有以下属性的对象: building:1
的键值对。由于它是第一个对象,因此它将被添加到新数组中。
假设我迭代的第二个对象是 id:58
。由于我的新 JSON 数组已经具有 building:1
的对象,因此我不想将该对象添加到我的新数组中。
我该如何去做呢?
请您参考如下方法:
我自己没有测试过,但它应该可以工作。
JSONArray arr = //your data object
JSONArray newArr = new JSONArray();
arr.stream().forEach(el -> {
Integer val = (Integer) ((JSONObject) el).get("building");
if (((List<Integer>) newArr.parallelStream().map(obj -> (Integer) ((JSONObject) obj).get("building"))
.filter(obj -> obj == val).collect(Collectors.toList())).isEmpty()) {
newArr.add(el);
}
});