整理一些Map比较常用方法
// 先定义一个Map
Map result = new ConcurrentHashMap();
// 下面就使用result;
1.Map添加元素
// 添加成功返回null,否则返回value;
result.put("key","value");
2.向Map添加指定的集合
Map str;
result.putall(str);
3.修改Map中的值
// 判断map中是否包含指定的key
if (map.containsKey("key")){
// 如果存在,可以直接put新的键值对。新的键值会自动覆盖之前的。
result.put("key","value");
}
4.删除Map中的所有键值
result.clear();
5.判断Map中是否包括指定的键
// 如果有则返回true,否则返回false;
boolean containsKey; // 不建议使用方法名作为变量名
containsKey=result.containsKey("key");
if(containsKey){
// 存在指定的Key
}else{
// 不存在指定的Key
}
6.判断Map中是否包括指定的值
// 如果有则返回true,否则返回false;
boolean containsValue; // 不建议使用方法名作为变量名
containsValue=result.containsValue("value");
if(containsValue){
// 存在指定的Value
}else{
// 不存在指定的Value
}
7.根据Map集合中的键获取所对应的值
String str;
str=result.get("Key");
8.判读Map是否为空
判断Map集合中是否有元素,如果没有则返回true,如果有元素则返回false(判断该Map是否为空)
if(result.isEmpty){
// 不为空
}else{
// 为空
}
9.删除Map中等于指定的键
// 删除Key为key值的元素
result.remove("key");
10.返回Map集合中元素个数
int count=result.size();
11.Map根据List下标获取数据
List<Map<String, Sting>> resultList = new ArrayList<>();
result=resultList.get(0); // get(下标)
12.遍历List集合转换为Map集合
List<Map<String, Sting>> resultList = new ArrayList<>();
String str;
for(Map Item:resultList){
str=Item.get("key");
}