20

Java で hashmap を繰り返し処理しようとしましたが、これはかなり簡単に実行できるはずです。ただし、次のコードではいくつかの問題が発生します。

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());

}

最初に、hm.keySet().iterator() で Iterator をキャストする必要がありました。そうしないと、「型の不一致: java.util.Iterator から Iterator に変換できません」と表示されたためです。しかし、その後、「メソッド hasNext() は型 Iterator に対して未定義です」、および「メソッド hasNext() は型 Iterator に対して未定義です」というメッセージが表示されます。

4

9 に答える 9

47

あなたのimportブロックが見えますか?Iterator間違ったクラスをインポートしたようです。

あなたが使うべきものはjava.util.Iterator

確認するには、次を試してください。

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

私は個人的に次のことをお勧めします。

Genericsインターフェースを使用したマップ宣言と宣言、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));
}

2015 年 3 月 5 日更新

Entry セットを反復すると、パフォーマンスが向上することがわかりました。

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

}

2017 年 10 月 3 日更新

Java8 とストリームの場合、ソリューションは次のようになります (@Shihe Zhang に感謝)

 hm.forEach((key, value) -> System.out.println(key + ": " + value))
于 2013-03-15T00:05:58.790 に答える
6

これには、ジェネリックと拡張 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());
}
于 2013-03-15T00:05:03.130 に答える
0
Map<String, Car> carMap = new HashMap<String, Car>(16, (float) 0.75);

// Maps のイテレータはありませんが、これを行うメソッドがあります。

        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");

        }
于 2013-03-15T00:44:15.013 に答える
0

HashMap で keySet イテレータを取得し、エントリを反復処理することを期待しています。

正しいコード:

    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's 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));

    }

EntrySet を使用して HashMap を反復処理する:

     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());  
    }           

以下のリンク のセクション - Traversing Through a HashMapを見てください。java-collection-internal-hashmap および HashMap によるトラバース

于 2019-06-21T15:33:23.580 に答える
0
  1. EntrySet() と for each ループの使用

       for(Map.Entry<String, String> entry: hashMap.entrySet()) {
         System.out.println("Key Of map = "+ entry.getKey() + 
                          " , value of map = " + entry.getValue() );
     }
    
  2. keyset() と for each ループの使用

             for(String key : hashMap.keySet()) {
                System.out.println("Key Of map = "+ key + " , 
                          value of map = " + hashMap.get(key) );
               }
    
  3. EntrySet() と Java Iterator の使用

          for(String key : hashMap.keySet()) {
            System.out.println("Key Of map = "+ key + " , 
                          value of map = " + hashMap.get(key) );
            }
    
  4. keyset() と Java Iterator の使用

         Iterator<String> keysIterator = keySet.iterator();
        while (keysIterator.hasNext()) {
            String key = keysIterator.next();
            System.out.println("Key Of map = "+ key + " , value of map = " + hashMap.get(key) );
       }
    

参考JavaでMapやHashMapを反復処理する方法

于 2021-01-27T17:01:47.527 に答える
0

最もクリーンな方法は、イテレータを (直接) まったく使用しないことです。

  • ジェネリックを使用してマップを入力します
  • 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)

于 2013-03-15T00:09:12.077 に答える
0

ここにいくつかの問題があります:

  • おそらく、正しい反復子クラスを使用していません。他の人が言ったように、使用してくださいimport java.util.Iterator
  • を使用したい場合は、 ではなくMap.Entry entry = (Map.Entry) iter.next();を使用する必要があります。キーまたはエントリを反復処理します。hm.entrySet().iterator()hm.keySet().iterator()
于 2013-03-15T00:10:13.370 に答える