让我们假设我有以下列表.

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

推荐答案

正如@LouisWasserman在the comment中所说,HashMap是完成这项任务的合适工具.

要将整个代码转换为流,您可以使用内置的collector groupingBy()summingInt作为下游收集器分组.

result = test.stream()
    .collect(Collectors.groupingBy(   // creates an intermediate map Map<String, Integer>
        StringInteger::getKey,                         // mapping a key
        Collectors.summingInt(StringInteger::getValue) // generating a value
    ))
    .entrySet().stream()
    .map(entry -> new StringInteger(entry.getKey(), entry.getValue()))
    .toList();

Java相关问答推荐

Saxon 9:如何从Java扩展函数中的net.sf.saxon.expr. XPathContent中获取声明的变量

同时运行JUnit测试和Selenium/Cucumber测试时出现问题

如何转换Tue Feb 27 2024 16:35:30 GMT +0800 String至ZonedDateTime类型""

为什么我的ArrayList索引的索引总是返回-1?

如何判断一个矩阵是否为有框矩阵?

如何获得执行人?

为什么不应用类型推断?

Java LocalTime.parse在本地PC上的Spring Boot中工作,但在Docker容器中不工作

Com.example.service.QuestionService中的构造函数的参数0需要找不到的类型为';com.example.Dao.QuestionDao;的Bean

在Spring Boot应用程序中导致";MediaTypeNotSupportdException&qot;的映像上载

内存和硬盘中的Zip不同,这会导致下载后的Zip损坏

STREAMS减少部分结果的问题

向Java进程发送`kill-11`会引发NullPointerException吗?

当我在Java中有一个Synchronized块来递增int时,必须声明一个变量Volatile吗?

在一行中检索字符分隔字符串的第n个值

在权限列表中找不到我的应用程序

AspectJ编织外部依赖代码,重新打包jar并强制依赖用户使用它

java中的网上购物车解析错误

关于正则表达式的一个特定问题,该问题与固定宽度负向后看有关

为什么当我输入变量而不是直接输入字符串时,我的方法不起作用?