public class HashMapReview{ public static void main(String [] args){ Map map=new HashMap(); map.put("Jack",3600); map.put("Tom",4200); map.put("Mary",5100); map.put("Smith",13000); //第一种 使用keySet()方法遍历 Set set=map.keySet(); for(Object o:set){ map.put(o,((Integer) map.get(o))+100); System.out.println("姓名:"+o+" \t"+"薪资:"+map.get(o)); } Iterator iterator=set.iterator(); while(iterator.hasNext()){ Object o=iterator.next(); map.put(o,((Integer) map.get(o))+100); System.out.println("姓名:"+o+" \t"+"薪资:"+map.get(o)); } System.out.println("======================="); //第二种 //使用entrySet()方法遍历 Set set1=map.entrySet(); for(Object o:set1) { Map.Entry o1 = (Map.Entry) o; map.put(o1.getKey(), (Integer) o1.getValue() + 100); System.out.println("姓名:" + o1.getKey() + " \t" + "薪资" + o1.getValue()); } Iterator iterator1=set1.iterator(); while(iterator1.hasNext()){ Object o2=iterator1.next(); Map.Entry o3=((Map.Entry) o2); map.put(o3.getKey(),(Integer)o3.getValue()+100); System.out.println("姓名:"+o3.getKey()+" \t"+"薪资:"+o3.getValue()); } System.out.println("================================="); //第三种方法,使用values()方法进行遍历 Collection c1=map.values(); for(Object o2:c1){ System.out.println(o2); } Iterator iterator2=c1.iterator(); while(iterator2.hasNext()){ Object o=iterator2.next(); System.out.println("薪资:"+o); } } }
HashMap遍历方式有三种,分别是keySet(),entrySet()和values(),调用keySet()输出Key的值可以直接使用加强for循环和迭代器的方式,不需要向下转型,但是想要改变value的值时可以用map.put()方法,利用map去重机制,当出现同样的key值时,新的value值会替代旧的value,key值保持不变,put括号内前面放置想要改变的value值对应的key,后面放置value值向下转型的Integer类型并加上数值即可完成增加value的int值。具体应用看上方代码。使用entrySet()方法遍历的时候要向下转型成entry的形式,这样才能够调用entry类里面的getKey()和getValue()两个方法,得到key值和value值。使用values()方法时,只能输出value的值,目前学的用法只有这点,今后有学习到再补充。