JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

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

wys521 2025-01-11 18:04:59 精选教程 71 ℃ 0 评论

本文主要讲述:字符串工具类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}

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

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表