HashMap集合是Map接口的一个实现类,它用于存储键值映射关系,但必须保证不能出现重复的键。如果存储了相同的键,后存储的值则会覆盖原有的值,简而言之就是:键相同,值覆盖。遍历Map中所有的键值对有两种方式,第一种就是先遍历Map集合所有的键,再根据键获取相应的值。
import java.util.*;
public class Text10 {
public static void main(String[] args) {
Map map=new HashMap();
map.put("1", "jfj");
map.put("2", "sg");
map.put("3", "gfg");
map.put("4", "sdgd");
//获取键的集合
Set keySet=map.keySet();
Iterator it=keySet.iterator();
while(it.hasNext()){
Object key=it.next();
Object value=map.get(key);
System.out.println(key+":"+value);
}
}
}
第二种方式是先获取集合中的所有的映射关系,然后从映射关系取出键和值。
import java.util.*; public class Text11 { public static void main(String[] args) { Map map=new HashMap(); map.put("1","a"); map.put("2","b"); map.put("3","c"); map.put("4","d"); map.put("5","e"); Set entrySet=map.entrySet(); Iterator it=entrySet.iterator(); while(it.hasNext()){ //获取集合中键值对映射关系 Map.Entry entry=(Map.Entry)(it.next()); Object key=entry.getKey(); Object value=entry.getValue(); System.out.println(key+":"+value); } } }
除此之外,在Map中,还提供了一个values()方法,通过这个方法可以直接获取Map中存储所有值的Collection集合
import java.util.*; public class Text12 { public static void main(String[] args) { Map map=new HashMap(); map.put("1","zz"); map.put("a","ff"); map.put("c","gg"); map.put("2","hh"); map.put("t","jgj"); Collection value=map.values(); Iterator it=value.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } }