Map集合和List集合以及Set集合一样,都有类似的一些方法,这里就不详细说明了。Collection集合由于存在迭代器的概念,因此对于集合的遍历比较方便,Map集合跟Collection集合又是两个不一样的集合分支,同时Map集合是以键值对的方式存储元素的,它的遍历方式就稍显复杂了,本篇博文主要讲解的是Map集合的遍历问题。
Map集合的遍历
- 通过键值对当中的key值来遍历
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class mapTest{
public static void main(String[] args) {
Map<Integer,String> map =new HashMap<>();
map.put(1,"张三");
map.put(2,"李四");
map.put(3,"王五");
map.put(4,"赵六");
//获取Map集合当中所有的key值
Set<Integer> set = map.keySet();
//通过Set集合的迭代器遍历集合获取Map集合的value值
Iterator<Integer> it = set.iterator();
while(it.hasNext()){
Integer key = it.next();
System.out.println(key+"="+map.get(key));
}
}
}
以上遍历过程也可使用增强for循环(foreach)
for(Integer key :set){
System.out.println(key+"="+map.get(key));
}
- 把Map集合直接全部转换成Set集合
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class mapTest{
public static void main(String[] args) {
Map<Integer,String> map =new HashMap<>();
map.put(1,"张三");
map.put(2,"李四");
map.put(3,"王五");
map.put(4,"赵六");
//Set集合中的元素类型是:Map.Entry
Set<Map.Entry<Integer,String>> set = map.entrySet();
Iterator<Map.Entry<Integer,String>> it = set.iterator();
while(it.hasNext()){
//遍历Set集合,每次取出来一个node
Map.Entry<Integer,String> node = it.next();
Integer key = node.getKey();
String value = node.getValue();
System.out.println(key+"="+value);
}
}
}
以上遍历过程也可使用增强for循环(foreach)
for(Map.Entry<Integer,String> node:set){
System.out.println(node.getKey()+"="+node.getValue());
}