How to sum of 2 arrays in group by ID used java 7

I have 2 arrays with variables:

String[] ID= String.valueOf("D123|;D456|;D123").split("\|;");
String[] amount= String.valueOf("20|;70|;10").split("\|;");

I want to SUM the amount with group by ID and get an output like this:

ID: D123
amount: 30,
ID: D456
amount: 70

Answer

As Java 7 does not have a lot of convenience methods in Map/HashMap available since Java 8, some additional coding is required to group by ID, calculate the sum, and print the results:

String[] ID = "D123|;D456|;D123".split("\|;");
String[] amount = "20|;70|;10".split("\|;");

assert ID.length == amount.length; // ensure both arrays have equal lengths

Map<String, Integer> map = new LinkedHashMap<>(); // keep insertion order

for (int i = 0; i < ID.length; i++) {
    String key = ID[i];
    Integer value = map.get(key);

    map.put(key, (null == value ? 0 : value.intValue()) + Integer.parseInt(amount[i]));
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println("ID: " + entry.getKey());
    System.out.println("amount: " + entry.getValue());
}

Leave a Reply

Your email address will not be published. Required fields are marked *