Map根据Key值进行排序

时间:2025-04-04 07:49:13

主要用到java8的新特性stream来实现排序的

 /**
     * @param map 判断的数据
     *            判断Map是否为空
     */
    public static <T, E> Boolean isNotEmpty(Map<T, E> map) {
        return !isEmpty(map);
    }

    /**
     * @param map           排序根据Key
     * @param keyExtractor  排序的字段  User::getAges
     * @param keyComparator 比较器  ((o1,o2) -> {
     *                      return  (o2);
     *                      })
     *                      map 内部排序根据Key
     */

    public static <T, E, U> Map<T, E> sortKey(Map<T, E> map, Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator) {
        Map<T, E> linkedMap = new LinkedHashMap<>();
        //先获取Map的Key值和Value值
        Set<T> key = ();

        //排序后
        List<T> list = (new ArrayList<>(key), keyExtractor, keyComparator);
        (item -> {
            (item, (item));
        });
        return linkedMap;
    }
  /**
     * @param list          集合
     * @param keyExtractor  比较的字段
     * @param keyComparator 比较器
     *                      List 排序正序
     *                      User user = new UserVO();
     *                      (39L);
     *                      User user1 = new UserVO();
     *                      (30L);
     *                      List<User> userList = new ArrayList<>();
     *                      (user);
     *                      (user1);
     *                      (user1);
     *                      List<User> list = toListSort(userList, User::getAges, (()));
     *                      返回30
     *                      List<User> list = toListSort(userList, User::getAges, ((o1, o2) -> {
     *                      return  (o2);
     *                      }));
     *                      返回30
     **/
    public static <T, U> List<T> toListSort(List<T> list, Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator) {

        return ().sorted((keyExtractor, keyComparator)).collect(());
    }