假设我有以下列表:
List<StringInteger> test = new ArrayList<>(); //StringInteger is just a pojo with String and int
test.add(new StringInteger("a", 1));
test.add(new StringInteger("b", 1));
test.add(new StringInteger("a", 3));
test.add(new StringInteger("c", 1));
test.add(new StringInteger("a", 1));
test.add(new StringInteger("c", -1));
System.out.println(test); // [{ a : 1 }, { b : 1 }, { a : 3 }, { c : 1 }, { a : 1 }, { c : -1 }]
我需要编写一个方法,它可以通过字符串键将项目合并并添加整数。因此,结果列表将为
[{ a : 5 }, { b : 1 }, { c : 0 }]
。我可以使用 HashMap 完成这个方法,但如果我按照这种方式 - 我必须创建 Map,然后使用增强 for 循环与 if(containsKey(...)),最后再将其转换回 List,这看起来有点冗余。
是否有更优雅的解决方案?我认为 Stream API 中的 flatMap 应该可以做到,但我无法弄清楚如何实现。
以下是我的笨拙解决方案。它可行,但我相信可以更简单地解决问题。
Map<String, Integer> map = new HashMap<>();
for (StringInteger stringInteger : test) {
if (map.containsKey(stringInteger.getKey())) {
int previousValue = map.get(stringInteger.getKey());
map.put(stringInteger.getKey(), previousValue + stringInteger.getValue());
} else {
map.put(stringInteger.getKey(), stringInteger.getValue());
}
}
List<StringInteger> result = map.entrySet()
.stream()
.map(stringIntegerEntry -> new StringInteger(stringIntegerEntry.getKey(), stringIntegerEntry.getValue()))
.collect(Collectors.toList());
System.out.println(result); // [{ a : 5 }, { b : 1 }, { c : 0 }]