标签:
最近正在做的高校云平台项目中接触Map比较多,关于map的使用不是很熟悉,所以在此将map的几个方法再次学习下。
提到Map集合接口就不能不提到Collection集合接口,map和Collection都是集合接口,Collection中包含了我们经常用的list和set子接口;而Map是与Collection处于平级的地位;Collection中存储的是一组对象,而Map存储的是一个键值对(key/value).
在Map对象中,Key是唯一的,不可重复的。null也可以作为key,但这样的key只能有一个;但是可以有一个或多个key所对应的value都是null。
当我们想判断map中是否存在某个key时,可以用方法containsKey()来判断,同样想判断是否存在value时用方法containsValue()来判断;代码如下:
<pre name="code" class="java">public static void main(String[] args) {
Map< Serializable, Serializable > map = new HashMap< Serializable, Serializable >();
map.put(null,null);
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
if (map.containsKey("a")) {
System.out.println("Key=Ture");
if (map.containsValue("1")) {
System.out.println("value=Ture");
}
}
}
Key=Ture value=Ture
Map中提供了一些常用的方法来取出Map中的数据,用的比较多的比如:entrySet()方法,;entrySet()的返回值是个Set集合,此集合的类型为Map.Entry。Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法,代码如下:
public static void main(String[] args) {
Map< Serializable, Serializable > map = new HashMap< Serializable, Serializable >();
map.put(null,null);
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
Set<Entry<Serializable, Serializable>> entrySet= map.entrySet();
System.out.println("entrySet="+entrySet);
for (Entry key : entrySet) {
System.out.println("key.getKey="+key.getKey()+" key.getValue()="+ key.getValue());
}
}
执行的结果如下:
entrySet=[null=null, a=1, b=2, c=3]
key.getKey=null key.getValue()=null
key.getKey=a key.getValue()=1
key.getKey=b key.getValue()=2
key.getKey=c key.getValue()=3
接下来要说的是keySet方法,keySet()方法返回值是Map中key值的集合,然后可以通过get(key)遍历来获取value值,代码如下:
public static void main(String[] args) {
Map< Serializable, Serializable > map = new HashMap< Serializable, Serializable >();
map.put(null,null);
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
Set keySet= map.keySet();
System.out.println("keySet="+keySet);
for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
Object key = (Object) iterator.next();
Object value = map.get(key);
System.out.println("key = "+key+ " value="+value);
}
}
执行的结果如下:
keySet=[null, a, b,c]
key = null value=null
key = a value=1
key = b value=2
key = c value=3
最后要说的是,map还有一个values()方法,values()方法返回值是Map中value值的集合,通过遍历可以取出value的值,代码如下:
public static void main(String[] args) {
Map<Serializable, Serializable> map = new HashMap<Serializable, Serializable>();
map.put(null, null);
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
Collection c = map.values();
System.out.println("map.values()=" + map.values());
for (Iterator iterator = c.iterator(); iterator.hasNext();) {
Object value = (Object) iterator.next();
System.out.println("value="+value);
}
}
map.values()=[null,1, 2, 3]
value=null
value=1
value=2
value=3
本文主要介绍了Map集合中entrySet()方法与keySet()、value()方法的使用,其中前两者取出的都是key和value的映射关系,只有最后的values取出的是集合中所以的值,没有键,也就没有了对应的映射关系。
标签:
原文地址:http://blog.csdn.net/zwk626542417/article/details/42290625