最近看到有个同事在遍历json数组的时候,用for循环写了一层有一层,那么是否有简便的写法呢?当然有了,下面就有用流的行驶,优雅的遍历数组,获取我们想要的数据
bash
public static void main(String[] args) {
String structure = "[{\"key\":\"111\",\"isRequired\":true,\"isNumber\":true,\"isFixed\":true},{\"key\":\"2\",\"isFixed\":true},{\"key\":\"3\",\"isNumber\":true},{\"key\":\"4\",\"isRequired\":true}]";
JSONArray jsonArray;
try {
jsonArray = JSON.parseArray(structure);
} catch (JSONException e) {
System.err.println("Invalid JSON format: " + e.getMessage());
return;
}
List<String> unitList = Optional.ofNullable(jsonArray)
.orElse(new JSONArray())
.stream()
.filter(item -> item instanceof JSONObject)
.map(item -> {
JSONObject jsonObject = (JSONObject) item;
String key = jsonObject.getString("key");
return key;
})
.collect(Collectors.toList());
System.out.println(unitList);
}