【发布时间】:2020-09-30 22:41:25
【问题描述】:
我有以下代码将年龄相同且得分最高的用户分组。
我现在有一个名为 Person 的对象而不是 Map<Person, List<String>>,并且在 person 类中有 Map Map<String,Double> nameScoreTogether;。我需要将输出及其信息(名称和相应的分数)存储在 person 对象的映射中,那么我该如何相应地更改代码?
输入:在Map<Person, String>的数据类型中:
{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)
=sharbel,
Person has at Age: 5 (Score: 0)
=thomas,
Person has at Age: 14 (Score: 60)
=thomy,
Person has at Age: 14 (Score: 50)
=angelos,
Person has at Age: 11 (Score: 50)
=musti,
Person has at Age: 11 (Score: 100)
=aloo,
Person has at Age: 2 (Score: 50)
=evi}
预期的输出是:
Person(score=50.0, age=1) - [sharbel=50.0]
Person(score=100.0, age=11) - [aloo=100.0, musti=50.0]
Person(score=50.0, age=12) - [Alex=50.0]
Person(score=60.0, age=14) - [thomy=60.0, angelos=50.0]
Person(score=50.0, age=2) - [evi=50.0]
Person(score=100.0, age=5) - [shi=100.0, Thomas=5.0]
Person(score=50.0, age=4) - [rafi=50]
Person(score=50.0, age=16) - [miki=50]
尝试代码:但现在我有List<Person>,其中有Map<String,Double>
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()))
);
类人:
public class Person {
int Age;
int lineScoreMax;
Map<String, Double> nameScoreTogether;
}
【问题讨论】:
-
如果我知道您有
Map<Person, String>并且您想将其转换为Map<Person, List<String>>? -
不,我想将其转换为 List
-
所以每个人都有 lineScore 这是最高分数,包括元组人名列表及其分数
-
你能修正你的输入和预期的输出吗?
Person has at Age: 1 (Score: 50). (Score: 50) =sharbel,为什么这一行有两个Score? -
更新帖子
标签: java arrays algorithm hashmap