如何在 java 8 中迭代 JSONArray

Posted

技术标签:

【中文标题】如何在 java 8 中迭代 JSONArray【英文标题】:How to iterate over a JSONArray in java 8 【发布时间】:2017-08-08 19:59:43 【问题描述】:

我有以下代码使用for loop 来迭代JSONArray 中的元素。

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.stream.IntStream;
    public class Pmt 
    private String[] patchInformation_svnRevisionpublic;
    private final Logger logger = Logger.getLogger(Pmt.class.getName());

        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 String[] getPublicGitCommitHashes(JSONArray jsonArray) 

            for (int i = 0; i < jsonArray.length(); i++) 
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                String tempName = (String) jsonObject.get(KEY_STRING);
                if (tempName.equals(COMMITS_IN_PATCH_IDENTIFIER)) 
                    JSONArray tempCommitsJSONArray = (JSONArray) jsonObject.get(VALUE_STRING);
                    //initializing the patchInformation_svnRevisionpublic array
                    patchInformation_svnRevisionpublic = new String[tempCommitsJSONArray.length()];
                    // for ommiting the white spaces at the begingin and end of the commits
                    IntStream.range(0, tempCommitsJSONArray.length()).forEach(j -> patchInformation_svnRevisionpublic[j] = ((String) tempCommitsJSONArray.get(j)).trim());

                    logger.info(" The commits hashes obtained from WSO2 PMT are successfully saved to an array");

                    System.out.println("The commit Ids are");
                    //            for printing all the commits ID associated with a patch
                    IntStream.range(0, patchInformation_svnRevisionpublic.length).mapToObj(i1 -> patchInformation_svnRevisionpublic[i1]).forEach(System.out::println);
                    System.out.println();
                    break;
                
            
            //to prevent from internaal representation by returning referecnce to mutable object
            String clonedPatchInformation_svnRevisionpublic[] = patchInformation_svnRevisionpublic.clone();
            return clonedPatchInformation_svnRevisionpublic;
        
    

如何使用Java 8 中的新功能(如streams APIforEach)来执行相同的任务。提前致谢

【问题讨论】:

既然你没有发布你的导入 - 你为 JSONArray 使用哪个库? @DmitryZvorygin 将相关导入添加到问题中 【参考方案1】:

这相当于 Java 8 流 API 中的代码。不是 100% 等价的,但您可以了解主要思想。

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<String> 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<Object> arrayToStream(JSONArray array) 
    return StreamSupport.stream(array.spliterator(), false);

【讨论】:

我们如何使用 distinct() 使用这种方法?似乎 JSONObject 仅使用相似而不是等于进行比较... @Myoch 如果我使用整个语句内联(不调用 arrayToStream 方法)它不起作用。为什么?

以上是关于如何在 java 8 中迭代 JSONArray的主要内容,如果未能解决你的问题,请参考以下文章

在 Java 8 中迭代枚举

将迭代循环体转换为功能代码Java 8

使用java 8迭代和过滤两个列表

java设计模式8.迭代子模式责任链模式命令模式

Java 8:计算 lambda 迭代的首选方法?

Java 8 流:迭代列表映射