Nid*_*257 5 java collections java-8 java-stream
我有一个班级说 Level (它只是一个用于理解的虚拟班级)。我想要一个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())));
}
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过Collectors.collectingAndThen()。
任何帮助表示赞赏。
提前致谢。
如果你不想让Level实施Comparable,你需要一个Comparator. 然后,您必须将创建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()));
}
}
Run Code Online (Sandbox Code Playgroud)
您修改后的工作代码如下所示,请参阅@4castle 评论:
public class Level implements Comparable<Level> {
int levelId;
public Level(int levelId) {
this.levelId = levelId;
}
@Override
public int compareTo(Level o) {
return Integer.compare(levelId, o.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(Level::getLevel, TreeMap::new,
Collectors.toSet()));
}
}
Run Code Online (Sandbox Code Playgroud)