【技术累积】【点】【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}

参考文章

posted @ 2018-10-30 14:15  韧还  阅读(731)  评论(0编辑  收藏  举报