0

我正在编写一个命令程序,其中有一个字符串列表,格式为:

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;
}

非常感谢你们。

4

2 回答 2

0

您当前的解决方案不一定按字典顺序对行名进行排序。在下面尝试我的解决方案。

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
于 2012-08-28T05:26:46.473 回答
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;
}
于 2012-08-29T00:37:36.580 回答