java 8 map Compratorを使って並べ替えます.
2333 ワード
1.java 8 streamにおけるソートに関する方法 Streamにおけるsorted方法 Comprator類 試験map を生成する. compparing方式new Comprator を使用します. compringInt を使用します.カスタムComprator 印刷結果
Stream sorted(Comparator super T> 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));
}
2.例 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"));
map.entrySet().stream()
.sorted(Comparator.comparing(entry -> entry.getKey().getScore()))
.forEach(entry -> System.out.println(entry.getValue()));
map.entrySet().stream()
.sorted(Comparator.comparingInt(entry -> entry.getKey().getScore()))
.forEach(entry -> System.out.println(entry.getValue()));
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]
[ , , ]