內容
- 是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;}
@Testpublic 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}
參考文章
- MapUtils常用方法
- Class MapUtils