我的情况:
SortedSet<Person> ss = new TreeSet<>();
ss.add(new Person("John", "Doe", 20));
ss.add(new Person("Max", "Power", 26));
ss.add(new Person("Bort", "Bort", 30));
ss.add(new Person("Scorpio", "McGreat", 56));
Map<Integer, List<Person>> list = ss.stream().collect(Collectors.groupingBy(p -> p.name.length()));
我需要将Map转换为
Map<Integer, Person>
。我知道我需要使用flatMap来完成这个任务,但我不知道如何操作。
到目前为止我尝试过的方法: 获取值集并对其进行flatMap操作。Map <Integer, Person> list2 = list.values()
.stream()
.flatMap(f -> f.stream())
.collect(Collectors.groupingBy(f -> f.name.length()); //doesn't work
问题: 据我所知,当你通过流创建映射表时,Java将返回值作为列表,那么如何对这些列表进行flatMap操作?
额外信息: compareTo的实现
@Override
public int compareTo(Person o) {
int cmp = this.surname.compareTo(o.surname);
if(cmp == 0){
cmp = this.name.compareTo(o.name);
}
return cmp;
}
声明:
我知道这个使用案例有点奇怪,因为我根据长度排序,并通过比较名称的长度来使用 compareTo。在我看来,对于这个问题,这并不重要,因为我总是会得到一个 Map<Key, List<Value>>
。
问题是:如何获得 Map<Key,Value>
?
toMap
收集器,将抛出合并器作为参数(在我看来是最好的选择)。 - Alexis C.