Java:Stream流遍历对象集合

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

前言

使用 Stream 流遍历元素为对象的集合。

实现

代码:

@GetMapping("/t16")
public void test16(){
	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);

	JSONArray age = jsonArray.stream()
			// 使用Stream流的map()方法来转换元素类型,同时使用 JSONObject.class::cast 方法来把JSONArray中的元素转为JSONObject。
			.map(JSONObject.class::cast)
			.filter(item -> item.getInteger("age") > 22)
			.collect(Collectors.toCollection(JSONArray::new));
	System.out.println(age);

	jsonArray = jsonArray.stream()
			// 使用类型强转,把元素强转为JSONObject。
			.filter(item -> ((JSONObject) item).getInteger("age")>=22)
			.collect(Collectors.toCollection(JSONArray::new));
	System.out.println(jsonArray);
}

输出:

[{"name":"langjialing3","age":23}]
[{"name":"langjialing2","age":22},{"name":"langjialing3","age":23}]

注:

  • Stream 流的 map() 方法用于将流中的每个元素映射为另一个元素,因此 map() 执行前后集合的元素个数是相同的,改变的是元素类型

总结

Java 中 Stream 流处理元素为对象的集合的操作。

赞助页面示例