java8 map 使用Comparator排序

2019-01-07  本文已影响0人  aix91

1. java8 stream里排序相关方法

Stream<T> sorted(Comparator<? super T> comparator);
@FunctionalInterface
public interface Comparator<T> {
//定义自己的Comparator
 int compare(T o1, T o2);
...  
//使用comparing方法定义Comparator
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor){
        Objects.requireNonNull(keyExtractor);
        return (Comparator<T> & Serializable)
            (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
    }
}
//使用comparingInt(按从小到大的顺序)
public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {
        Objects.requireNonNull(keyExtractor);
        return (Comparator<T> & Serializable)
            (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
    }

2. 实例

       Map<TopicNLPEnum, List<String>> 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<Map.Entry<TopicNLPEnum, List<String>>> 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]
[小说, 言情, 历史]
上一篇下一篇

猜你喜欢

热点阅读