zoukankan      html  css  js  c++  java
  • Map工具类,排序及转对象

    import com.alibaba.fastjson.JSON;
    import com.google.common.collect.Maps;
    
    import java.util.Map;
    
    /**
     * @ClassName MapUtil
     * @Author ZhangRF
     * @CreateDate 2020/08/12
     * @Decription
     */
    public class MapUtil {
        /**
         * 根据map的key排序
         *
         * @param map    待排序的map
         * @param isDesc 是否降序,true:降序,false:升序
         * @return 排序好的map
         * @author zero 2019/04/08
         */
        public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean isDesc) {
            Map<K, V> result = Maps.newLinkedHashMap();
            if (isDesc) {
                map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed())
                        .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;
        }
    
        /**
         * 根据map的value排序
         *
         * @param map    待排序的map
         * @param isDesc 是否降序,true:降序,false:升序
         * @return 排序好的map
         * @author zero 2019/04/08
         */
        public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean isDesc) {
            Map<K, V> result = Maps.newLinkedHashMap();
            if (isDesc) {
                map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue().reversed())
                        .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;
        }
    
        /**
         * map转对象
         *
         * @param map
         * @param clazz
         * @param <T>
         * @return
         */
        public static <T> T parse(Map<?, ?> map, Class<T> clazz) {
            return JSON.parseObject(JSON.toJSONString(map), clazz);
        }
    }
  • 相关阅读:
    让man 显示中文
    对‘pthread_create’未定义的引用
    gcc和arm-linux-gcc区别
    ubuntu14.04下arm-linux-gcc 4.5.1的安装与配置
    MakeCode 递归生成资源文件
    Swagger 增加 DocumentFilter 隐藏不需要显示的接口
    Razor 模板自己渲染出结果 string
    .net core API 统一拦截错误
    内网机(无网络安装 .NET Core win开发环境
    netcore web.config ConnectionStrings AppSettings
  • 原文地址:https://www.cnblogs.com/zhangrongfei/p/15667269.html
Copyright © 2011-2022 走看看