1

Here I want to add the amount & value which is coming in list such as amount of one list + amount of another list, value of one list + value of another list with Java program , How can I achieve this

Input JSON

{
 "data": [
           {
              "amount": "100",
              "value": "200",
            
           },
           {
              "amount": "200",
              "value": "200",
           }
    ]
}

required output

"amount":300
"value":400
2
  • Should the result be {"amount": 300, "value": 400} where both amount and value fields are added? Also, input JSON does not seem to be valid representation of the list. Commented Oct 15, 2020 at 9:15
  • Right @AlexRudenko Commented Oct 15, 2020 at 9:17

2 Answers 2

1

define a DTO like this:

class AmountInfo {
    int value;
    int amount;
}

use the follow code to get what you want:

int value = 0;
int amount = 0;
for (AmountInfo amountInfo : amountInfoList) {
    value += amountInfo.getValue();
    amount += amountInfo.getAmount();
}

AmountInfo result = new AmountInfo(value, amount);
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.