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”);
}

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九霄王

我们一起为这个世界努力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值