Итератор над HashMap в Java

Я попытался перебрать hashmap в Java, что должно быть довольно простой задачей. Однако следующий код дает мне некоторые проблемы:

HashMap hm = new HashMap();

hm.put(0, "zero");
hm.put(1, "one");

Iterator iter = (Iterator) hm.keySet().iterator();

while(iter.hasNext()) {

    Map.Entry entry = (Map.Entry) iter.next();
    System.out.println(entry.getKey() + " - " + entry.getValue());

}

Во-первых, мне нужно было запустить Iterator на hm.keySet(). iterator(), потому что в противном случае он сказал: "Тип несоответствия: невозможно преобразовать из java.util.Iterator в Iterator". Но затем я получаю "Метод hasNext() имеет значение undefined для типа Iterator" и "Метод hasNext() - undefined для типа Iterator".

Ответы

Ответ 1

Можем ли мы увидеть ваш блок import? потому что кажется, что вы импортировали неправильный класс Iterator.

Тот, который вы должны использовать, это java.util.Iterator

Чтобы убедиться, попробуйте:

java.util.Iterator iter = hm.keySet().iterator();

Я лично предлагаю следующее:

Объявление карты с использованием Generics и объявление с использованием Map<K,V> интерфейса Map<K,V> и создание экземпляра с использованием требуемой реализации HashMap<K,V>

Map<Integer, String> hm = new HashMap<>();

и для цикла:

for (Integer key : hm.keySet()) {
    System.out.println("Key = " + key + " - " + hm.get(key));
}

ОБНОВЛЕНИЕ 3/5/2015

Выяснилось, что перебор набора Entry будет лучше с точки зрения производительности:

for (Map.Entry<Integer, String> entry : hm.entrySet()) {
    Integer key = entry.getKey();
    String value = entry.getValue();

}

ОБНОВЛЕНИЕ 3/3/2017

Для Java8 и потоков ваше решение будет (Спасибо @Shihe Zhang)

 hm.forEach((key, value) -> System.out.println(key + ": " + value))

Ответ 2

Для этого вам действительно нужно использовать generics и расширенный цикл for:

Map<Integer, String> hm = new HashMap<>();
hm.put(0, "zero");
hm.put(1, "one");

for (Integer key : hm.keySet()) {
    System.out.println(key);
    System.out.println(hm.get(key));
}

http://ideone.com/sx3F0K

Или версия entrySet():

Map<Integer, String> hm = new HashMap<>();
hm.put(0, "zero");
hm.put(1, "one");

for (Map.Entry<Integer, String> e : hm.entrySet()) {
    System.out.println(e.getKey());
    System.out.println(e.getValue());
}

Ответ 3

С Java 8:

hm.forEach((k, v) -> {
    System.out.println("Key = " + k + " - " + v);
});

Ответ 4

Самый чистый способ - не (напрямую) использовать итератор вообще:

  • введите вашу карту с помощью дженериков.
  • используйте цикл foreach для перебора записей:

Вот так:

Map<Integer, String> hm = new HashMap<Integer, String>();

hm.put(0, "zero");
hm.put(1, "one");

for (Map.Entry<Integer, String> entry : hm.entrySet()) {
    // do something with the entry
    System.out.println(entry.getKey() + " - " + entry.getValue());
    // the getters are typed:
    Integer key = entry.getKey();
    String value = entry.getValue();
}

Это намного эффективнее, чем повторение ключей, потому что вы избегаете n вызовов get(key).

Ответ 5

Несколько проблем здесь:

  • Вероятно, вы не используете правильный класс итератора. Как говорили другие, используйте import java.util.Iterator
  • Если вы хотите использовать Map.Entry entry = (Map.Entry) iter.next();, вам нужно использовать hm.entrySet().iterator(), а не hm.keySet().iterator(). Либо вы итерации по клавишам, либо по вводам.

Ответ 6

Map<String, Car> carMap = new HashMap<String, Car>(16, (float) 0.75);

//нет итератора для Карт, но есть методы для этого.

        Set<String> keys = carMap.keySet(); // returns a set containing all the keys
        for(String c : keys)
        {

            System.out.println(c);
        }

        Collection<Car> values = carMap.values(); // returns a Collection with all the objects
        for(Car c : values)
        {
            System.out.println(c.getDiscription());
        }
        /*keySet and the values methods serve as "views" into the Map.
          The elements in the set and collection are merely references to the entries in the map, 
          so any changes made to the elements in the set or collection are reflected in the map, and vice versa.*/

        //////////////////////////////////////////////////////////
        /*The entrySet method returns a Set of Map.Entry objects. 
          Entry is an inner interface in the Map interface.
          Two of the methods specified by Map.Entry are getKey and getValue.
          The getKey method returns the key and getValue returns the value.*/

        Set<Map.Entry<String, Car>> cars = carMap.entrySet(); 
        for(Map.Entry<String, Car> e : cars)
        {
            System.out.println("Keys = " + e.getKey());
            System.out.println("Values = " + e.getValue().getDiscription() + "\n");

        }

Ответ 7

Итератор через keySet выдаст вам ключи. Вы должны использовать entrySet если хотите перебирать записи.

HashMap hm = new HashMap();

hm.put(0, "zero");
hm.put(1, "one");

Iterator iter = (Iterator) hm.entrySet().iterator();

while(iter.hasNext()) {

    Map.Entry entry = (Map.Entry) iter.next();
    System.out.println(entry.getKey() + " - " + entry.getValue());

}

Ответ 8

Вы получаете итератор keySet для HashMap и ожидаете перебора записей.

Правильный код:

    HashMap hm = new HashMap();

    hm.put(0, "zero");
    hm.put(1, "one");

    //Here we get the keyset iterator not the Entry iterator
    Iterator iter = (Iterator) hm.keySet().iterator();

    while(iter.hasNext()) {

        //iterator next() return an Integer that is the key
        Integer key = (Integer) iter.next();
        //already have the key, now get the value using get() method
        System.out.println(key + " - " + hm.get(key));

    }

Итерация по HashMap с использованием EntrySet:

     HashMap hm = new HashMap();
     hm.put(0, "zero");
     hm.put(1, "one");
     //Here we get the iterator on the entrySet
     Iterator iter = (Iterator) hm.entrySet().iterator();


     //Traversing using iterator on entry set  
     while (iter.hasNext()) {  
         Entry<Integer,String> entry = (Entry<Integer,String>) iter.next();  
         System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
     }  

     System.out.println();


    //Iterating using for-each construct on Entry Set
    Set<Entry<Integer, String>> entrySet = hm.entrySet();
    for (Entry<Integer, String> entry : entrySet) {  
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
    }           

Посмотрите на раздел - Обход по HashMap в ссылке ниже. java-collection-internal-hashmap и обход через HashMap