You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不使用GSON,如何对比两个ArrayList并输出匹配的文本值

问题描述

在不使用GSON的情况下,从给定JSON数据的chores数组中,提取那些value存在于myFilterObj的chore数组中的对象的text值。

给定JSON数据

{
    "chores": [
        {
            "text": "Wash the car",
            "value": 1
        },
        {
            "text": "Mow the lawn",
            "value": 2
        },
        {
            "text": "Vaccumm the floor",
            "value": 3
        },
        {
            "text": "Walk the dog",
            "value": 4
        }
    ],
    "myFilterObj": {
        "chore": [
            1,
            2
        ]
    }
}

已编写的代码

JSONArray allChores = data.getJSONArray("chores");
JSONArray myChores = myFilterObj.getJSONArray("chore"); 
ArrayList<Object> listdata1 = new ArrayList<Object>();
ArrayList<Object> listdata2 = new ArrayList<Object>();
if (allChores != null) {
    for (int i = 0; i < allChores.length(); i++) {
        //Adding each element of JSON array into ArrayList
        listdata1.add(allChores.get(i));
    }
}
if (myChores != null) {
    for (int i = 0; i < myChores.length(); i++) {
        //Adding each element of JSON array into ArrayList
        listdata2.add(myChores.get(i));
    }
}
//comapare allChores.value to myChores(value)
//printout allChores.text on match 

额外测试数据

chores数组

[ 
    {
        "text":"Wash the car",
        "value":1
    }, 
    {
        "text":"Mow the lawn",
        "value":7
    }, 
    {
        "text":"Vaccumm the floor",
        "value":2
    }, 
    {
        "text":"Walk the dog",
        "value":8
    }
]

过滤数组

[
    1,
    2,
    3
]
解决方案

不需要使用removeAll,直接用contains方法检查每个任务的value是否在过滤列表中即可。修改后的完整代码如下:

JSONArray allChores = data.getJSONArray("chores");
JSONArray myChores = myFilterObj.getJSONArray("chore"); 
ArrayList<Object> listdata1 = new ArrayList<Object>();
ArrayList<Object> listdata2 = new ArrayList<Object>();
if (allChores != null) {
    for (int i = 0; i < allChores.length(); i++) {
        listdata1.add(allChores.get(i));
    }
}
if (myChores != null) {
    for (int i = 0; i < myChores.length(); i++) {
        listdata2.add(myChores.get(i));
    }
}

// 遍历所有任务,匹配过滤条件并输出text
for (Object obj : listdata1) {
    JSONObject choreObj = (JSONObject) obj;
    int value = choreObj.getInt("value");
    if (listdata2.contains(value)) {
        String text = choreObj.getString("text");
        System.out.println(text);
    }
}

关键说明

  • listdata2.contains(value):直接判断当前任务的value是否在过滤列表中,适合小规模数据场景
  • listdata1中存储的是JSONObject实例,必须强制类型转换后才能调用getInt、getString方法提取字段
  • 针对额外测试数据,运行后会输出Wash the car和Vaccumm the floor,符合过滤预期

内容的提问来源于stack exchange,提问作者Jasper Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 21:06:30