You should have a POJO representing the item in the input list and you can implement method add(Pojo) to accumulate total value for multiple POJOs:
public class Pojo {
private int amount;
private int value;
// getters/setters/constructor(s)
public void add(Pojo pojo) {
this.amount += pojo.amount;
this.value += pojo.value;
}
}
Test (reading JSON, calculating total, writing the result):
String json = "[{\n"
+ " \"amount\": 100,\n"
+ " \"value\": 200\n"
+ "},\n"
+ "{\n"
+ " \"amount\": 200,\n"
+ " \"value\": 200\n"
+ "}]";
ObjectMapper mapper = new ObjectMapper();
List<Pojo> list = mapper.readValue(json, new TypeReference<>() {});
Pojo total = new Pojo();
/*
for (Pojo item : list) {
total.add(item);
}
*/
list.forEach(total::add); // replacing previous loop with `forEach` and instance method reference
String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(total);
System.out.println(result);
output
{
"amount" : 300,
"value" : 400
}
{"amount": 300, "value": 400}where bothamountandvaluefields are added? Also, input JSON does not seem to be valid representation of the list.