package javaMap; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class FourIterateMap { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Map<String,String> map = new HashMap(); map.put("1", "lw"); map.put("2", "wk"); map.put("3", "dr"); map.put("4", "cc"); map.put("5", "sl"); map.put("6", "vd"); //1.遍历keySet,通过get(key)获取 // 性能:(慢而且效率低!尽量不要用) System.out.println("--------------用keyset------------------"); for(String key : map.keySet()) { System.out.println("key1是" + key + "value1是" + map.get(key)); } //2.若只需要map中的键或者值,直接keySet()或者values() // 性能:该方法比entrySet遍历在性能上稍好(快了10%),而且代码更加干净。 System.out.println("--------------用keySet()或者values()------------------"); for(String key : map.keySet()) { System.out.println("key2是" + key); } for(String value : map.values()) { System.out.println("value2是" + value); } //3.iterator entrySet // 性能:跟for-each(即2方式)差不多 System.out.println("--------------用iterator entrySet()------------------"); Iterator<Map.Entry<String, String>> entry = map.entrySet().iterator(); while(entry.hasNext()) { Map.Entry<String, String> entries = entry.next();// 切记,在while里一定要将entry.next()给entries System.out.println("key3是" + entries.getKey() + "value3是" + entries.getValue()); } //for each entrySet 大容量是推荐(最常用) // 使用时一定要对map进行判空 System.out.println("--------------用for each entrySet()------------------"); for(Map.Entry<String, String> entry1 : map.entrySet()) { System.out.println("key4是" + entry1.getKey() + "value4是" + entry1.getValue()); } } }
Map遍历的四种方式及选择
猜你喜欢
转载自lopez.iteye.com/blog/2216304
今日推荐
周排行