JDK8 新特性-Map 集合或数组 value 排序实现

直接上代码:
Map collect = noWhiteListMap.entrySet().stream()
        .sorted(Comparator.comparing(entry -> entry.getValue().split(",").length,Comparator.reverseOrder()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));

在java 8中按照此步骤对map进行排序.

  1. 将 Map 转换为 Stream
  2. 对其进行排序
  3. Collect and return a new LinkedHashMap (保持顺序)

 其中  Comparator 接口有两个 comparing  方法

/**
     * Accepts a function that extracts a sort key from a type {@code T}, and
     * returns a {@code Comparator} that compares by that sort key using
     * the specified {@link Comparator}.
      *
     * 

The returned comparator is serializable if the specified function * and comparator are both serializable. * * @apiNote * For example, to obtain a {@code Comparator} that compares {@code * Person} objects by their last name ignoring case differences, * *

{@code
     *     Comparator cmp = Comparator.comparing(
     *             Person::getLastName,
     *             String.CASE_INSENSITIVE_ORDER);
     * }
* * @param the type of element to be compared * @param the type of the sort key * @param keyExtractor the function used to extract the sort key * @param keyComparator the {@code Comparator} used to compare the sort key * @return a comparator that compares by an extracted key using the * specified {@code Comparator} * @throws NullPointerException if either argument is null * @since 1.8 */ public static Comparator comparing( Function keyExtractor, Comparator keyComparator) { Objects.requireNonNull(keyExtractor); Objects.requireNonNull(keyComparator); return (Comparator & Serializable) (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1), keyExtractor.apply(c2)); } /** * Accepts a function that extracts a {@link java.lang.Comparable * Comparable} sort key from a type {@code T}, and returns a {@code * Comparator} that compares by that sort key. * *

The returned comparator is serializable if the specified function * is also serializable. * * @apiNote * For example, to obtain a {@code Comparator} that compares {@code * Person} objects by their last name, * *

{@code
     *     Comparator byLastName = Comparator.comparing(Person::getLastName);
     * }
* * @param the type of element to be compared * @param the type of the {@code Comparable} sort key * @param keyExtractor the function used to extract the {@link * Comparable} sort key * @return a comparator that compares by an extracted key * @throws NullPointerException if the argument is null * @since 1.8 */ public static > Comparator comparing( Function keyExtractor) { Objects.requireNonNull(keyExtractor); return (Comparator & Serializable) (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2)); }
利用 comparing 比较方法传入 比较的函数 和 自定义排序的 如降序  通过 LinkedHashMap 保存顺序

你可能感兴趣的:(java)