Java中Map的使用

1. Map的命名空间:java.util.Map
(1)Map只是一个接口,并不是一个类
(2)Map中的Key和Value不能为Null,以Key-Value键值对作为存储元素实现的哈希结构。
(3)Key唯一,Value可以重复

2.Map的创建
Map的创建主要有以下几种:
//接口的实现
Map<String,String> map1 = new HashMap<String,String>();
Map<String,String> map2 = new Hashtable<String,String>();

//红黑树的实现
Map<String,String> map3 = new TreeMap<String,String>();

3.向Map中添加值
map1.put(“1”, “frist”);
map1.put(“2”, “second”);
map1.put(“3”, “three”);
map1.put(“4”, “four”);

4. 求Map的大小,判断Map是否为Null,Map是否包含每个Key和Value
4.1 求Map的大小
int len = map1.size();
4.2 判断Map是否为Null
if(map1.isEmpty())
{
System.out.print(“Map中没有Key和Value”+ “\r\n”);
}
4.3 Map是否包含每个Key和Value
if(map1.containsKey(“2”))
{
System.out.print(“存在关键词为2,其值=” + map1.get(“2”) + “\r\n”);
}
if(map1.containsValue(“three”))
{
System.out.print(“存在值为thre” + “\r\n”);
}

**5. Map的遍历形式
**5.1 Set遍历Map
(1)转换为Iterator之后,进行遍历输出
Set keys = map1.keySet(); //返回key
if(keys != null)
{
Iterator iterator = keys.iterator();
while(iterator.hasNext())
{
Object Keys = iterator.next();
System.out.print("输出Map中的关键值 = " + Keys + “\r\n”);
System.out.print("输出Map中的值 = " + map1.get(Keys) + “\r\n”); //每次去Map取值
}
}
(2)采用for来遍历输出
for(String key : map1.keySet())
{
System.out.print("输出Map中的关键值对应的值 = " + map1.get(key) + “\r\n”); //每次去Map中取值
}

5.2 Collection 遍历Map
(1)转换为Iterator或者List之后,进行遍历输出
Collection value = map1.values();
if(value != null)
{
//Iterator输出值
Iterator iterators = value.iterator();
while(iterators.hasNext())
{
Object Values = iterators.next();
System.out.print("输出Map中的值 = " + Values + “\r\n”);
}
//List输出值
List list = new ArrayList();
list.addAll(value);
for(String s:list)
{
System.out.print("输出Map中的值 = " + s + “\r\n”);
}
}
(2)采用for来遍历输出
for(String v : map1.values())
{
System.out.print("输出Map中的值 = " + v + “\r\n”);
}
5.3 Map的内部接口 Entry遍历Map
(1)转换为Iterator或者List之后,进行遍历输出
Set entryset = map1.entrySet(); //包含key和Value
if(entryset!=null)
{
Iterator<Map.Entry<String, String>> iterator = entryset.iterator();
while(iterator.hasNext())
{
Map.Entry<String, String> entry = iterator.next();
String key = entry.getKey();
String values = entry.getValue();
System.out.print("输出Map中的Key和Value值 = " + key + “,” + values + “\r\n”);
}
}
(2)采用for来遍历输出
for(Map.Entry<String, String> entry : map1.entrySet())
{
System.out.print("输出Map中的Key和Value值 = " + entry.getKey() + “,” + entry.getValue() + “\r\n”);
}

猜你喜欢

转载自blog.csdn.net/weixin_42631192/article/details/84675036
今日推荐