1.通过迭代器遍历
public class Testmap {
public static void main(String[] args) throws Exception{
Map<Integer,String> map=new HashMap<>();
map.put(1,"hello");
map.put(2,"hello");
map.put(3,"baby");
//1.将map转换为set集合
Set<Map.Entry<Integer,String>> set=map.entrySet();
//2.获取iterator对象
Iterator<Map.Entry<Integer,String>> iterator=set.iterator();
while(iterator.hasNext()){
Map.Entry<Integer,String> entry=iterator.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}
2.基于迭代器,以foreach遍历
public class Testmap {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "hello");
map.put(3, "baby");
System.out.println(map);
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
3.通过遍历key遍历Map
public class Testmap {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "hello");
map.put(3, "baby");
System.out.println(map);
for (Integer key : map.keySet()) {
String value = map.get(key);
}
}
}
4.通过Value遍历
public class Testmap {
public static void main(String[] args) throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "hello");
map.put(3, "baby");
System.out.println(map);
for (String value : map.values()){
System.out.println(value);
}
}
}