100个Java工具类之33:Map工具类Apache之MapUtils

100个Java工具类之33:Map工具类Apache之MapUtils

编码文章call10242025-05-30 11:19:1615A+A-

本文主要讲述:字符串工具类Apache之


org.apache.commons.collections.MapUtils

见名知义,MapUtil是操作Map的工具类,但大多数方法应用场景十分有限,CollectionUtils提供的方法完全够用,因此这里只做介绍,不推荐使用

避免代码重复,影响阅读体验,因此将打印方法省略。

一、获取map的值

Map<String, Object> map = new HashMap<>();
map.put("name", "zhangSan");
map.put("age", 100);
Map<String, Object> otherMap = new HashMap<>();
otherMap.put("sex", "男");
otherMap.put("money", 999.99);
map.put("other", otherMap);
Map<String, String> newMap = MapUtils.getMap(map, "other");
输出:{money=999.99, sex=男}
String name = MapUtils.getString(map, "name");
输出:zhangSan
int age = MapUtils.getInteger(map, "age");
输出:100

二、判空

boolean flag = MapUtils.isEmpty(new HashMap<>());
输出:true
boolean flag = MapUtils.isNotEmpty(new HashMap<>());
输出:false

三、Map中放入二维数组

Object[][] str = {{"userName", "admin"},{"password", 123456}};
Map<String, Object> map = new HashMap<>();
MapUtils.putAll(map, str);
输出:{password=123456, userName=admin}

四、将map长度固定,无法新增key

Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
Map<String, String> newMap = MapUtils.fixedSizeMap(map);
newMap.put("key2", "value2");
输出:java.lang.IllegalArgumentException: Cannot put new key/value pair - Map is fixed size

五、将map的key和value值对换位置

Map<String, String> map = new HashMap<>();
map.put("key", "value");
Map<String, String> newMap = MapUtils.invertMap(map);
输出:{value=key}

六、Map转Properties

Map<String, String> map = new HashMap<>();
map.put("port", "80");
Properties ps = MapUtils.toProperties(map);
输出:{port=80}

今天的分享就到这里,感谢大家的阅读,喜欢的给个赞吧~

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4