将多个字段置于一个字符串中,然后使用集合来分组以查找每个组的总和
想象一下,我有以下字段:
> String name1
> String name2
> String name3
> BigDecimal amount
我想使用一个 String
对它们进行分组,这是Name1,Name2和Name3的串联。
例如:
name1 = hi
name2 = am
name3 = sarah
String newString = hiamsarah
然后,在通过链式字符串
设法将对象分组后,我想获得每个组的量
字段的总和。
这可能吗?
我已经尝试了任何可能的方法,但是我无法通过它。另外,我是收藏品的新手。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您的实例包含在
list
中,并且在您的类中,有一种返回链式名称的方法,您可以使用终端操作收集来使用集合流和组。 (collectors.tomap())
。链式值可以用作密钥,
bigdecimal
值作为对应于密钥的值,最后可以通过求和bigdecimal
值来处理碰撞案例。由于您没有提供所指的类的代码,因此我声明了一个名为
myClass
包含3字符串
字段和bigdecimal
的类。代码>。这是代码的片段:测试类实现(
myClass
):这里还有一个链接来测试代码:
https://ideone.com/il1zq8
Supposing that your instances are contained within a
List
and that within your class there is a method to return the chained names, you could use the collection stream and group by your instances with the terminal operationcollect(Collectors.toMap())
.The chained value can be used as the key, the
BigDecimal
value as the value corresponding to the key and finally the collision cases can be handled by summing theBigDecimal
values.Since you didn't provide the code of the class you're referring to, I declared a class named
MyClass
containing the 3String
fields and theBigDecimal
. Here is a snippet of the code:Test class implementation (
MyClass
):Here there is also a link to test the code:
https://ideone.com/IL1ZQ8
collectors.groupingbyby
一起使用。 +collector.reducing
假设给定类是记录自Java 14以来提供了以下实现:
输出:输出:
String::join
, the first argument is a delimiter which can be an empty stringString.join("", name1, name2, name3)
Collectors.groupingBy
+Collectors.reducing
Assuming that the given class is implemented as a record provided since Java 14, the following implementation is offered:
Output: