Java:使用迭代器在JSONArray中删除或修改元素

郎家岭伯爵 2024年03月18日 222次浏览

前言

在 List 或 JSONArray 的遍历中无法直接使用 remove() 方法来删除元素,这是因为 remove() 方法会改变集合的大小,这会直接影响到遍历操作。

我们可以使用 Iterator 迭代器来进行操作。

实现

代码:

@GetMapping("/t17")
public void test17(){
	JSONArray jsonArray = new JSONArray();

	JSONObject jsonObject1 = new JSONObject();
	jsonObject1.put("name", "langjialing");
	jsonObject1.put("age", "21");
	jsonArray.add(jsonObject1);

	JSONObject jsonObject2 = new JSONObject();
	jsonObject2.put("name", "langjialing2");
	jsonObject2.put("age", "22");
	jsonArray.add(jsonObject2);

	JSONObject jsonObject3 = new JSONObject();
	jsonObject3.put("name", "langjialing3");
	jsonObject3.put("age", "23");
	jsonArray.add(jsonObject3);

	JSONObject jsonObject4 = new JSONObject();
	jsonObject4.put("name", "langjialing3");
	jsonObject4.put("age", "22");
	jsonArray.add(jsonObject4);

	Iterator<Object> iterator = jsonArray.iterator();
	while (iterator.hasNext()){
		JSONObject item = (JSONObject)iterator.next();
		if ("22".equals(item.getString("age"))){
			item.put("age1", "good");
		} else {
			System.out.println(item);
			iterator.remove();
		}
	}

	System.out.println(jsonArray);
}

输出:

{"name":"langjialing","age":"21"}
{"name":"langjialing3","age":"23"}
[{"name":"langjialing2","age":"22","age1":"good"},{"name":"langjialing3","age":"22","age1":"good"}]

总结

Java 中使用 Iterator 迭代器遍历 List 或 JSONArray 等集合,进行元素的删除或修改操作。

赞助页面示例