Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

collections - Merge two maps with same keys in java and add the value together


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Either the values in col map should be of numeric type to allow for arithmetic operations, or another map Map<String, Integer> should be created to store the results of calculations.

Also, there's no need to have a nested loop to calculate the sums while reading the data because the calculation results will be incorrect.

There are several ways to accumulate the sums in the map per key.

  1. Use method Map::compute
Map<String, Integer> col = new HashMap<>(); // changed value type to Integer
// ...
Integer number = 0;
while (cmd.hasNextLine()) {
    String line = cmd.nextLine();
    if (line.charAt(9) == 'A') {
        number = Integer.valueOf(line.substring(23, 28)); 
        Name = line.substring(29, 34);
        col.compute(Name, (key, prev) -> (prev == null ? 0 : prev) + number);     
    }
    // no need for nested loop
}

// print map contents
col.forEach((name, sum) -> System.out.print("%s %04d%n", name, sum));
  1. Use method Map::merge along with Integer::sum which can be replaced with a lambda (sum, val)-> sum + val:
Integer number = 0;
while (cmd.hasNextLine()) {
    String line = cmd.nextLine();
    if (line.charAt(9) == 'A') {
        number = Integer.valueOf(line.substring(23, 28)); 
        Name = line.substring(29, 34);
        col.merge(Name, number, Integer::sum);     
    }
}
// print map contents
col.forEach((name, sum) -> System.out.print("%s %04d%n", name, sum));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...