我有一个类说级别(它只是一个用于理解的虚拟类)。
我想要一个排序的 TreeMap<Level,Set<String>>
基于levelId。
请找到下面的代码
import java.util.*;
import java.util.stream.Collectors;
public class Level {
int levelId;
public Level(int levelId) {
this.levelId = levelId;
}
public static Level getLevel(String name){
return new Level(name.length());
}
public static void main(String[]args){
Set<String> names=new HashSet<>();
names.add("Mahesh");
names.add("Ram");
names.add("Rita");
Map<Level, Set<String>> map = names.stream().collect(
Collectors.groupingBy(name->Level.getLevel(name),
Collectors.mapping(name->name,Collectors.toSet())));
}
}
我也试过 Collectors.collectingAndThen()
.
感谢任何帮助。
提前致谢。
最佳答案
如果你不想让Level
实现Comparable
,你需要一个Comparator
。然后,您必须将使用此分隔符作为 map 工厂创建 TreeMap
的 lambda 表达式传递给 groupingBy
收集器:
public class Level {
int levelId;
public Level(int levelId) {
this.levelId = levelId;
}
public static Level getLevel(String name){
return new Level(name.length());
}
public int getLevelId() {
return levelId;
}
public static void main(String[]args){
Set<String> names=new HashSet<>();
names.add("Mahesh");
names.add("Ram");
names.add("Rita");
Comparator<Level> c = Comparator.comparingInt(Level::getLevelId);
Map<Level, Set<String>> map = names.stream()
.collect(Collectors.groupingBy(
Level::getLevel, () -> new TreeMap<>(c), Collectors.toSet()));
}
}
关于java - 如何使用流从列表中对 TreeMap 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46702432/