[英]How to sum up similar values of Map together
我在下面有这个输入,它显示了一个人在什么年龄有什么分数。 这存储在 HashMap 中,例如Map<Person, Information>
Person class 只有double: getScore()
返回分数的int:getAge()
和返回年龄的 class 信息有: class 中没有属性名称。
{Person has at Age: 12 (Score: 50)
=alex,
Person has at Age: 16 (Score: 50)
=miki,
Person has at Age: 5 (Score: 100)
=shi,
Person has at Age: 4 (Score: 50)
=rafi,
Person has at Age: 1 (Score: 50). (Score: 50)
=sharbel,
Person has at Age: 5 (Score: 0). (Score: 0)
=thomas,
Person has at Age: 14 (Score: 60). (Score: 60)
=thomy,
Person has at Age: 14 (Score: 50). (Score: 50)
=angelos,
Person has at Age: 11 (Score: 50). (Score: 50)
=musti,
Person has at Age: 11 (Score: 100). (Score: 100)
=aloo,
Person has at Age: 2 (Score: 50). (Score: 50)
=evi}
我需要的是,将年龄相同且得分最高的用户分组。 预期的 output 应该是这样的:
{Person has at Age: 12 (Score: 50)
=alex,
Person has at Age: 16 (Score: 50)
=miki,
Person has at Age: 5 (Score: 100)
=[shi,thomas], // those are together
Person has at Age: 4 (Score: 50)
=rafi,
Person has at Age: 1 (Score: 50)
=sharbel,
Person has at Age: 14 (Score: 60).
=[thomy , angelos], // those are together and we consider the biggest score 60
Person has at Age: 11 (Score: 100)
=[musti, aloo], // those are together and we consider the biggest score 100
Person has at Age: 2 (Score: 50)
=evi}
所以请注意[thomy, angelos]
和[musti, aloo]
在一起,这是因为他们的年龄相同,我们认为他们之间的得分最高。
我尝试了许多不同的方法,但没有成功,因此我没有尝试任何实现。
您可以像这样使用 stream :
Map<Person, List<String>> result = origin.entrySet().stream()
.collect(Collectors.groupingBy(e -> e.getKey().getAge())).entrySet().stream()
.collect(Collectors.toMap(
e -> e.getValue().stream()
.map(Map.Entry::getKey)
.max(Comparator.comparing(Person::getScore))
.get(),
e -> e.getValue().stream()
.map(Map.Entry::getValue)
.collect(Collectors.toList()))
);
但我建议使用另一种方法,使用简单的类而不是复杂的 Map。
输出
Person(score=50.0, age=1) - [sharbel]
Person(score=100.0, age=11) - [aloo, musti]
Person(score=50.0, age=12) - [alex]
Person(score=60.0, age=14) - [thomy, angelos]
Person(score=50.0, age=2) - [evi]
Person(score=100.0, age=5) - [shi, thomas]
Person(score=50.0, age=4) - [rafi]
Person(score=50.0, age=16) - [miki]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.