zoukankan      html  css  js  c++  java
  • 【技术累积】【点】【java】【29】MapUtils

    内容

    • 是Apache组织下的commons-collections包中的工具类
    <dependency>
                <groupId>commons-collections</groupId>
                <artifactId>commons-collections</artifactId>
                <version>3.2.1</version>
            </dependency>
    
    • Map操作相关的,最常用和null值相关

    使用

    • 取值
    public static String getString(final Map map, final Object key) {
            if (map != null) {
                Object answer = map.get(key);
                if (answer != null) {
                    return answer.toString();
                }
            }
            return null;
        }
        
    public static String getString( Map map, Object key, String defaultValue ) {
            String answer = getString( map, key );
            if ( answer == null ) {
                answer = defaultValue;
            }
            return answer;
        }
    
    

    取值,二元参数无默认字符串;

    同样有针对其他类型的取值方法;

    • 赋值
    putAll()
    
    public static void safeAddToMap(Map map, Object key, Object value) throws NullPointerException {
            if (value == null) {
                map.put(key, "");
            } else {
                map.put(key, value);
            }
        }
    

    一个是putAll,数组加入map中;

    一个是safeAdd,不加入null值;

    • 操作
    //排序
    public static Map orderedMap(Map map) {
            return ListOrderedMap.decorate(map);
        }
     
    //反转,key value互换
    public static Map invertMap(Map map) {
            Map out = new HashMap(map.size());
            for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
                Map.Entry entry = (Map.Entry) it.next();
                out.put(entry.getValue(), entry.getKey());
            }
            return out;
        }    
    
    @Test
        public void testMapUtils() {
            Map<String,String> map = new HashMap<>();
            map.put("shit","Happens");
            map.put("0","1");
            log.info("{}",MapUtils.getString(map,"shi222t","hhhhh"));
            log.info("order:{}",MapUtils.orderedMap(map));
            log.info("invert:{}",MapUtils.invertMap(map));
        }
        
    [INFO ] 2018-10-30 14:07:42,144 method:com.andy.dot.TestAllDots.testMapUtils(TestAllDots.java:177)
    hhhhh
    [INFO ] 2018-10-30 14:07:42,276 method:com.andy.dot.TestAllDots.testMapUtils(TestAllDots.java:178)
    order:{0=1, shit=Happens}
    [INFO ] 2018-10-30 14:07:42,277 method:com.andy.dot.TestAllDots.testMapUtils(TestAllDots.java:179)
    invert:{Happens=shit, 1=0}
    

    参考文章

  • 相关阅读:
    K2路由器刷机教程
    GitBook Editor使用教程
    source tree使用教程
    github与github网站push神器
    tgp助手开启逆战游戏无反应
    如何计算服务器指标参数
    排序--堆排序算法
    排序--希尔排序算法
    排序--直接插入排序算法
    排序--冒泡排序算法
  • 原文地址:https://www.cnblogs.com/andy1202go/p/9876571.html
Copyright © 2011-2022 走看看