• java map 根据value排序取前n


    package com.cnblogs.test;
    
    import java.util.List;
    import java.util.Map;
    
    import com.google.common.collect.ImmutableMap;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    
    /**
     * @author toutou 2019/03/17
     */
    public class Java8future {
    
        public static void main(String[] args) {
            Map<String, Integer> map = ImmutableMap.of("gq", 7, "aa", 9, "zs", 66, "vv", 3);
            System.out.println("原始的map:" + map);
            System.out.println("key降序:" + sortByKey(map, true, 2));
            System.out.println("key升序:" + sortByKey(map, false, 2));
            System.out.println("value降序:" + sortByValue(map, true, 2));
            System.out.println("value升序:" + sortByValue(map, false, 2));
        }
    
        /**
         * Sort map by value
         *
         * @param map map source
         * @param isDesc 是否降序,true:降序,false:升序
         * @param limit 取前几条
         * @return 已排序map
         */
        public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean isDesc, int limit) {
            Map<K, V> result = Maps.newLinkedHashMap();
            if (isDesc) {
                map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue().reversed()).limit(limit)
                        .forEach(e -> result.put(e.getKey(), e.getValue()));
            } else {
                map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue())
                        .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
            }
            return result;
        }
    
        /**
         * Sort map by key
         *
         * @param map 待排序的map
         * @param isDesc 是否降序,true:降序,false:升序
         * @param limit 取前几条
         * @return 已排序map
         */
        public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean isDesc, int limit) {
            Map<K, V> result = Maps.newLinkedHashMap();
            if (isDesc) {
                map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed()).limit(limit)
                        .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
            } else {
                map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey())
                        .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
            }
            return result;
        }
    }
  • 相关阅读:
    luogu P5473 [NOI2019]I 君的探险 交互 随机 二分 分治 整体二分
    218. The Skyline Problem
    315. Count of Smaller Numbers After Self
    493. Reverse Pairs
    307. Range Sum Query
    1409. Queries on a Permutation With Key
    如果redis没有设置expire,他是否默认永不过期?
    同步调用和异步调用
    缓存穿透、缓存击穿、缓存雪崩概念及解决方案
    Python实现发送邮件---转载至https://www.cnblogs.com/liuqingzheng/articles/10072695.html
  • 原文地址:https://www.cnblogs.com/toutou/p/sort_map.html
Copyright © 2020-2023  润新知