Map的特性
Map 是一种键-值对(key-value)集合Map 集合中的每一个元素都包含一个键对象和一个值对象。其中,键对象不允许重复,而值对象可以重复,并且值对象还可以是 Map 类型的,就像数组中的元素还可以是数组一样。
Map 有两组值,因此遍历时可以只遍历值的集合,也可以只遍历键的集合,也可以同时遍历。Map 以及实现 Map 的接口类(如 HashMap、TreeMap、LinkedHashMap、Hashtable 等)都可以用以下几种方式遍历
1).通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作。
Map<String, String> map = new HashMap<>();
for (String key : map.keySet()) {
String value = map.get(key);
}
2).使用for-each循环遍历key 或 values(一般只要key或value值时这样写较为方便)
Map<String, String> map = new HashMap<>();
for (String key : map.keySet()) {
System.out.println(key);
}
//打印值集合
for (String value : map.values()) {
System.out.println(value);
}
3).Entry实现Map遍历(常用)
Map<String, String> map = new HashMap<>();
Set<Map.Entry<String, String>> entries =map.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}
4).使用迭代器(Iterator)遍历
Map<String, String> map = new HashMap<>();
Iterator<Map.Entry<String, String>> iterator =map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key+":"+value);
}
有疑问的伙伴尽可留言互动!!
Thanks!