java 8 map Compratorを使って並べ替えます.

2333 ワード

1.java 8 streamにおけるソートに関する方法
  • Streamにおけるsorted方法
  • Stream sorted(Comparator super T> comparator);
    
  • Comprator類
  • @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> 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"));
    
  • compparing方式new Comprator
  • を使用します.
    map.entrySet().stream()
           .sorted(Comparator.comparing(entry -> entry.getKey().getScore()))
           .forEach(entry -> System.out.println(entry.getValue()));
    
  • compringInt
  • を使用します.
    map.entrySet().stream()
           .sorted(Comparator.comparingInt(entry -> entry.getKey().getScore()))
           .forEach(entry -> System.out.println(entry.getValue()));
    
  • カスタムComprator
  • 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]
    [  ,   ,   ]