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.
- 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));
- 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));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…