Java-Map专题
1、Java-遍历map的四种方法
https://blog.csdn.net/jiuba_wb/article/details/124411040
https://www.jianshu.com/p/3d1fb84b2b63
//第三种:推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
Map<String, List<CourseHourTotalHourBo>> map = Maps.newHashMap();
List<CourseHourTotalHourBo> list = Lists.newArrayList();
CourseHourTotalHourBo courseHourTotalHourBo = new CourseHourTotalHourBo();
courseHourTotalHourBo.setContainerId("xxx");
list.add(courseHourTotalHourBo);
userGroupMap.put("user1", list);
// 转换后的集合
map .forEach((uid, myList) -> {
System.out.println(uid + "—" + myList.get(0).getContainerId());
});
2、 Map创建并初始化
private final static HashMap<String, Integer> map = new HashMap<String, Integer>(){{
put("key1", 0);
put("key2", 1);
put("key3", 2);
}};
初始化一个有序的map
private final static Map<String, List<String>> erjidanweiMapping = new LinkedHashMap<String, List<String>>() {{
put("沈变公司", Lists.newArrayList("特变电工沈阳变压器集团有限公司"));
put("衡变公司", Lists.newArrayList("特变电工衡阳变压器有限公司"));
put("新变厂", Lists.newArrayList("特变电工股份有限公司新疆变压器厂", "天津市特变电工变压器有限公司"));
put("工业文化旅游公司", Lists.newArrayList("新疆特变电工工业文化旅游有限责任公司", "特变电工股份有限公司后勤管理分公司"));
}};
erjidanweiMapping.keySet() 的结果就是有序的。
3、map转list
如果从一个map中取值再转成list报错(JSON.parseArray),就将这个map先转成String,再使用JSON.parseObject或JSON.parseArray:
Map<String, Object> lastTargetRecordThisYearBy = xxx;
//关键
String s = JSON.toJSONString(lastTargetRecordThisYearBy);
JSONObject jsonObject = JSON.parseObject(s);
List<String> chengnuoshuList = JSON.parseArray(jsonObject.getOrDefault("chengnuoshu","[]").toString(),String.class);
4、ImmutableMap返回空值对象
if (CollectionUtils.isEmpty(userIdList)) {
ImmutableMap<String, PaasUserOVo> = ImmutableMap.of();
}
正文到此结束