Stream 里的 sorted 方法
Stream sorted(Comparator super T> comparator);
Comparator 类
@FunctionalInterface
public interface Comparator {
// 定义自己的Comparator
int compare(T o1, T o2);
...
// 使用comparing方法定义Comparator
public static > Comparator comparing(Function super T, ? extends U> keyExtractor){
Objects.requireNonNull(keyExtractor);
return (Comparator & Serializable)
(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}
}
// 使用comparingInt(按从小到大的顺序)
public static Comparator comparingInt(ToIntFunction super T> keyExtractor) {
Objects.requireNonNull(keyExtractor);
return (Comparator & Serializable)
(c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
}
生成测试 map
Map> map = new HashMap<>();
map.put(TopicNLPEnum.SIMILAR, Arrays.asList("小说1", "言情1", "历史1"));
map.put(TopicNLPEnum.RELATIVE, Arrays.asList("小说3", "言情3", "历史3"));
map.put(TopicNLPEnum.ORIGIN, Arrays.asList("小说", "言情", "历史"));
map.put(TopicNLPEnum.TAGS, Arrays.asList("小说2", "言情2", "历史2"));
使用 comparing 的方式 new 一个 Comparator
map.entrySet().stream()
.sorted(Comparator.comparing(entry -> entry.getKey().getScore()))
.forEach(entry -> System.out.println(entry.getValue()));
使用 comparingInt
map.entrySet().stream()
.sorted(Comparator.comparingInt(entry -> entry.getKey().getScore()))
.forEach(entry -> System.out.println(entry.getValue()));
自定义 Comparator
Comparator>> comp = (o1, o2) -> o1.getKey().getScore() - o2.getKey().getScore();
map.entrySet().stream()
.sorted(comp)
.forEach(entry -> System.out.println(entry.getValue()));
打印结果
[小说3, 言情3, 历史3]
[小说2, 言情2, 历史2]
[小说1, 言情1, 历史1]
[小说, 言情, 历史]