【问题标题】:Java stream doesn't recognise typeJava 流无法识别类型
【发布时间】:2018-07-26 11:28:06
【问题描述】:
((JSONArray) JsonUtils.parseStringToJsonObject(response.getResponseBody()).get("firstArray")).stream()
                .map(s->((JSONArray) s).get(1).toString()).collect(Collectors.toList())

为什么这段代码 sn-p 会返回一个 Object 而不是 List?

(响应类型为IHttpResponse<String>

【问题讨论】:

  • 您将其投射到对象? (JSONArray)...这是一个对象吗?
  • 这是哪个 JSONArray? (它不是 Java API 类。您应该添加适当的标签。)
  • 我正在使用 org.json.simple。这个 JSONArray 来自这里:mvnrepository.com/artifact/com.googlecode.json-simple/…
  • ListObject?我不明白这个问题。你能详细说明并添加更多代码吗?
  • 所以问题是->当我想用这个代码sn-p返回一个方法时,它会返回对象而不是列表。我想返回一个列表,但它不允许这样做。

标签: java java-8 java-stream collectors


【解决方案1】:

以下代码应该可以工作

初始化 JSONArray 的示例代码

    JSONArray jsonArray =new JSONArray();
    JSONObject j1 = new JSONObject();
    j1.put ("key", "Stack");
    JSONObject j2 = new JSONObject();
    j2.put ("key", "Overflow");
    jsonArray.add(j1);
    jsonArray.add(j2);

将 JSONArray 转换为 List。您的代码中有几个问题。第一个是,您在 map 函数中使用 JSONArray ,它应该是 JSONObject 。第二个是map返回Stream,我们需要将其类型转换为Stream<String>

 List<String> output =  arrayToStream(jsonArray)
                                 .map(JSONObject.class::cast)
                                 .map(s -> s.get("key").toString())
                                 .collect(Collectors.toList());

将JSONArray转换为Stream&lt;Object&gt;的Util方法

private static Stream<Object> arrayToStream(JSONArray array) {
        return StreamSupport.stream(array.spliterator(), false);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 2018-11-03
    相关资源
    最近更新 更多