我正在编写一个命令程序,其中我有一个字符串列表,格式为:
AAA 100 BBB 200 CCC 300 AAA 50
所需的输出是对第一列进行分组并汇总第二列。
AAA 150 BBB 200 CCC 300
我使用下面的代码并且它有效,但只是想知道它应该是一种更优雅的方式吗?
public static Map<String, Integer> summarizeData(List<String> lines) {
Map<String, Integer> map = new HashMap<String, Integer>();
String[] temp;
for (String line : lines) {
temp = line.split("\\s+");
if (map.containsKey(temp[0])) {
int value = Integer.valueOf(temp[1])
+ (Integer) map.get(temp[0]);
map.put(temp[0], value);
} else {
map.put(temp[0], Integer.valueOf(temp[1]));
}
}
return map;
}
非常感谢你们。
答案 0 :(得分:0)
您当前的解决方案不一定按字典顺序对行名称进行排序。 Try我的解决方案如下。
public static Map<String, Integer> compile(final List<String> input) {
final Map<String, Integer> map = new TreeMap<String, Integer>();
final Pattern space = Pattern.compile("\\s+");
for (final String line : input) {
final String[] parts = space.split(line, 0);
final String name = parts[0];
final int addendum = Integer.valueOf(parts[1]);
final Integer old = map.get(name);
map.put(name, old == null ? addendum : old + addendum);
}
return map;
}
...生产:
AAA 150 BBB 200 CCC 300
答案 1 :(得分:0)
您的代码可以正常工作,但我会将其重构为:
public static Map<String, Object> summarizeData(List<String> lines) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (String line : lines) {
String[] temp = line.split("\\s+");
Integer total = map.get(temp[0]);
total = total == null ? 0 : total;
map.put(temp[0], total + Integer.valueOf(temp[1]));
}
return map;
}