简体   繁体   中英

Java: How to add a JSON object to a JSON array only if one of the elements don't already exist

Say I have a JSON array (inside of a JSON object) of JSON objects.

{
  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}
  ]
}

I want to cycle through the array and add each JSON object to a new JSON array, but ONLY if one of the values of a certain key ( building ) hasn't already been added to the new JSON array.

For example, if I iterate over the JSON array and get to id:45 , I want to add that object to my new JSON array, but only if there isn't already an object with a key-value pair of building:1 . Since it'd be the first object, it would get added into the new array.

Let's say the second object I was iterating over was id:58 . Being that my new JSON array already has an object with building:1 , I would not want to add that object to my new array.

How would I go about doing this?

I did not test this myself but it should work.

    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);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM