让我们假设我有以下列表.
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
,然后使用if(containsKey(...))
的增强型for
循环,然后将它转换回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 }]