Jonny
1
求时长的和
@Test
public void count() {
String json = "[\n" +
" [\n" +
" {\n" +
" \"label\": \"时长(天)\",\n" +
" \"required\": true,\n" +
" \"name\": \"DURATION\",\n" +
" \"type\": \"number\",\n" +
" \"value\": \"0.5\",\n" +
" \"dateFormatType\": 0,\n" +
" \"editable\": false\n" +
" },\n" +
" {\n" +
" \"label\": \"同行人员\",\n" +
" \"required\": false,\n" +
" \"name\": \"COLLEAGUES\",\n" +
" \"type\": \"text\",\n" +
" \"editable\": false\n" +
" }\n" +
" ],\n" +
" [\n" +
" {\n" +
" \"label\": \"时长(天)\",\n" +
" \"required\": true,\n" +
" \"name\": \"DURATION\",\n" +
" \"type\": \"number\",\n" +
" \"value\": \"0.9\",\n" +
" \"dateFormatType\": 0,\n" +
" \"editable\": false\n" +
" },\n" +
" {\n" +
" \"label\": \"同行人员\",\n" +
" \"required\": false,\n" +
" \"name\": \"COLLEAGUES\",\n" +
" \"type\": \"text\",\n" +
" \"editable\": false\n" +
" }\n" +
" ]\n" +
"]\n" +
"\n";
JSONArray jsonArray = JSON.parseArray(json);
List<Object> results = jsonArray.stream().map(obj -> ((JSONArray) obj).stream().filter(arr -> {
JSONObject jsonObject = (JSONObject) arr;
return "DURATION".equals(jsonObject.getString("name"));
}).map(arr -> ((JSONObject) arr).get("value"))).collect(Collectors.toList()).stream().flatMap(d -> d).collect(Collectors.toList());
System.out.println(results);
}
试试看这个?
public static BigDecimal sum(JSONArray jsonArray) {
BigDecimal retVal = new BigDecimal(0);
for (int i = 0; i < jsonArray.size(); i++) {
Object json = jsonArray.get(i);
if (json instanceof JSONArray) {
retVal = retVal.add(sum((JSONArray) json));
} else {
JSONObject jsonObject = (JSONObject) json;
if ("DURATION".equals(jsonObject.get("name"))) {
retVal = retVal.add(jsonObject.getBigDecimal("value"));
}
}
}
return retVal;
}
我测试了一下
JSONArray jsonArray = JSON.parseArray(json);
BigDecimal result = sum(jsonArray);
System.out.println(result); // 1.4
Jonny
3
lambda
版【不考虑性能】
Double sum = jsonArray.stream().map(obj -> ((JSONArray) obj).stream().filter(arr -> {
return "DURATION".equals(((JSONObject) arr).getString("name"));
}).mapToDouble(arr -> Double.parseDouble(((JSONObject) arr).getString("value")))).collect(Collectors.toList()).stream().flatMapToDouble(d -> d).sum();
System.out.println(sum);
1 Like