Remove all elements except one from JSONArray of JSONObjects

后端 未结 3 743
离开以前
离开以前 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:01

    If you're seeking a functional style solution, you can wrap the Iterator into a Stream and then do whatever you want.

    One of the functional solutions:

    JSONArray newJsonArray =
            StreamSupport.stream(jsonArray.spliterator(), false)
                         .filter(JSONObject.class::isInstance)
                         .map(JSONObject.class::cast)
                         .filter(j -> j.has("a"))
                         .collect(collectingAndThen(toList(), JSONArray::new));
    

    Note: The solution above does not modify the original JSONArray. Following the principles of functional programming one should prefer collecting into a new object rather than modifying the existing one.

提交回复
热议问题