Map映射集合实现类HashMap的介绍和迭代遍历方法

发布于 2011-10-16 | 更新于 2020-09-20

Map也就是映射集合

java.util 接口 Map<K,V> 类型参数: K - 此映射所维护的键的类型 不能重复 V - 映射值的类型 可以重复

Map的一个实现类:

HashMap:没有顺序(和HashSet一样)

注意:HashSet重复的值会报错,HashMap重复的值会替换掉。 HashMap中的Key和Value不能保存原始数据类型,只能保存数据类型的封包类如String,Integer…

遍历Map的三种方法

获取Key的集合:

keySet()

返回此映射中所包含的键的 Set 视图。

Key不能重复,所以使用Set作为返回值。

//第一种遍历Map的方法
Set set = map.keySet();
for(Iterator iter = set.iterator(); iter.hasNext()😉{
String key = iter.next();
String value = map.get(key);
System.out.println(key + “:” + value);
}

获取Values的集合:

values()

返回此映射所包含的值的 Collection 视图。

Values可以重复,所以使用Collection作为返回值。

//第二种遍历Map的方法
Collection collection = map.values();
for(Iterator iter = collection.iterator(); iter.hasNext()😉{
System.out.println(iter.next());
}

使用Map的内部类Map.Entry遍历集合:

Set<Map.Entry<K,V>> entrySet()

返回此映射所包含的映射关系的 Set 视图。

下面通过获取Map的内部类Map.Entry遍历集合:

//第三种遍历Map的方法
Set<Map.Entry<String, String>> set1 = map.entrySet();
for(Iterator<Map.Entry<String, String>> iter = set1.iterator(); iter.hasNext()😉{
Map.Entry<String, String> entry = iter.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + “:” + value);
}

本文作者: arthinking

本文链接: https://www.itzhai.commap-map-collection-implementation-class-hashmap-and-iterate-through-methods-of-presentation.html

版权声明: 版权归作者所有,未经许可不得转载,侵权必究!联系作者请加公众号。

×
IT宅

关注公众号及时获取网站内容更新。