Remove all elements except one from JSONArray of JSONObjects

后端 未结 3 742
离开以前
离开以前 2021-01-27 00:56

I have a JSONArray (org.json) like this:

[
    { \"a\": \"a\" },
    { \"b\": \"a\" },
    { \"c\": \"a\" },
    { \"d\": \"a\" },
    { \"e\": \"a\" },
    { \"         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-27 01:15

    What we can do is map all JSONObjects to a List if they contain the key a. Then we can create a new JSONArray from that List of objects, which in this case is only 1.

    You can technically do this in a single line but it looks a bit worse IMO.

    List objects = IntStream.range(0, array.length())
            .filter(index -> array.get(index) instanceof JSONObject)
            .mapToObj(array::getJSONObject)
            .filter(object -> object.has("a"))
            .collect(Collectors.toList());
    
    JSONArray reduced = new JSONArray(objects);
    

提交回复
热议问题