<dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency>
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; }
取值,二元參數無默認字符串;html
一樣有針對其餘類型的取值方法;java
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中;apache
一個是safeAdd,不加入null值;api
//排序 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}