生活随笔
收集整理的這篇文章主要介紹了
【技术累积】【点】【java】【29】MapUtils
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
內容
- 是Apache組織下的commons-collections包中的工具類
<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;}
取值,二元參數無默認字符串;
同樣有針對其他類型的取值方法;
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
轉載于:https://www.cnblogs.com/andy1202go/p/9876571.html
總結
以上是生活随笔為你收集整理的【技术累积】【点】【java】【29】MapUtils的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。