要使用Stream过滤JSONArray对象中的某个值,可以按照以下步骤进行操作:

  1. 将JSONArray对象转换为Stream对象,可以使用JSONArray的stream()方法。
  2. 使用filter()方法对Stream对象进行过滤,传入一个Predicate lambda表达式,用于判断某个元素是否符合过滤条件。
  3. 调用collect()方法将过滤后的元素收集到一个新的List或者其他数据结构中。

下面是一个示例代码,演示如何使用Stream过滤JSONArray对象中的某个值:

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String jsonString = "[{\"name\":\"John\", \"age\":30}, {\"name\":\"Alice\", \"age\":25}, {\"name\":\"Bob\", \"age\":35}]";
        JSONArray jsonArray = new JSONArray(jsonString);

        // 使用Stream过滤年龄大于30的对象
        List<JSONObject> filteredList = jsonArray.stream()
                .map(obj -> (JSONObject) obj) // 将Stream中的元素转换为JSONObject
                .filter(obj -> obj.getInt("age") > 30) // 过滤年龄大于30的对象
                .collect(Collectors.toList()); // 收集过滤后的元素到List中

        // 输出过滤后的结果
        for (JSONObject obj : filteredList) {
            System.out.println(obj);
        }
    }
}

运行上述代码,将会输出年龄大于30的对象:

{"name":"John","age":30}
{"name":"Bob","age":35}
``

原文地址: https://www.cveoy.top/t/topic/iNKE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录