【java】Java遍历HashMap的五种方式

1.单独遍历key,value (获取单个key或value效率高)

for(String k:maps.keySet()){
            System.out.println(k+":"+maps.get(k));
        }
     
for(String value:maps.values()){
            System.out.println(value);
        }

2.Map.Entry<.......>泛型遍历(效率高,推荐使用)

Map map = new HashMap();
for (Map.Entry entry : map.entrySet()) {
  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

3.Iterator

Iterator key,value遍历

Iterator iterator = maps.keySet().iterator();
        while(iterator.hasNext()){
            String key = iterator.next();
            System.out.println(key+":"+maps.get(key));
        }

Iterator iter= maps.values().iterator();
        while(iter.hasNext()){
            System.out.println(iter.next());
        }

Iterator Map.Entry<.......>泛型遍历

Map map = new HashMap();
Iterator> entries = map.entrySet().iterator();
while (entries.hasNext()) {
  Map.Entry entry = entries.next();
  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

4.java8中使用forEach进行遍历

maps.forEach((k,v)-> System.out.println("Item :"+k+" Count:"+v));

5.键找值遍历(效率低)

Map map = new HashMap();
for (Integer key : map.keySet()) {
  Integer value = map.get(key);
  System.out.println("Key = " + key + ", Value = " + value);
}

 

 

Mapitems=new HashMap<>();
        items.put("A",10);
        items.put("B",20);
        items.put("C",30);
        items.put("D",40);
        items.put("E",50);
        items.put("F",60);
 
        //1.使用entrySet的迭代器
        Iterator iter1=items.entrySet().iterator();
        while(iter1.hasNext()){
            Map.Entry entry=(Map.Entry)iter1.next();
            System.out.println("Item :"+entry.getKey()+" Count:"+entry.getValue());
 
        }
 
        //2.使用keySet的迭代器
        Iterator iter2=items.keySet().iterator();
        while(iter2.hasNext()){
            String key=(String) iter2.next();
            System.out.println("Item :"+key+" Count:"+items.get(key));
        }
 
        //3.使用for循环利用EntrySet进行遍历
        for(Map.Entryentry:items.entrySet()){
            System.out.println("Item :"+entry.getKey()+" Count:"+entry.getValue());
        }
 
        //4.使用for循环利用keySet进行遍历
        for (String key:items.keySet()){
            System.out.println("Item :"+key+" Count:"+items.get(key));
        }
 
        //5.java8中使用forEach进行遍历
        items.forEach((k,v)-> System.out.println("Item :"+k+" Count:"+v));

 

你可能感兴趣的:(◆,java,◆)