How to iterate over a JSONArray in java 8

前端 未结 1 1759
梦谈多话
梦谈多话 2021-01-02 11:11

I have the following code which is using a for loop to iterate over the elements in a JSONArray.

import org.apache.log4j.Logger;
i         


        
1条回答
  •  离开以前
    2021-01-02 11:58

    This is equivalent of or code in Java 8 stream API. Not 100% equivalent, but you can get the main idea.

    private static final String COMMITS_IN_PATCH_IDENTIFIER = "patchInformation_svnRevisionpublic";  //key used to identify the commits in a patch from JSON response received from PMT
    private static final String KEY_STRING = "name";
    private static final String VALUE_STRING = "value";
    
    public List getCommitIds (JSONArray array) {
         return arrayToStream(array)
                .map(JSONObject.class::cast)
                .filter(o -> o.get(KEY_STRING).equals(COMMITS_IN_PATCH_IDENTIFIER))
                .findFirst()
                .map(o -> (JSONArray) o.get(VALUE_STRING))
                .map(Main::arrayToStream)
                .map(commits ->
                        commits.map(Object::toString)
                                .map(String::trim)
                                .collect(Collectors.toList())
                )
                .orElseGet(Collections::emptyList);
    }
    
    @Nonnull
    private static Stream arrayToStream(JSONArray array) {
        return StreamSupport.stream(array.spliterator(), false);
    }
    
        

    0 讨论(0)
    提交回复
    热议问题