60

次の LinkedHashMap 宣言があります。

LinkedHashMap<String, ArrayList<String>> test1

私のポイントは、このハッシュマップをどのように反復できるかです。各キーについて、対応する配列リストを取得し、配列リストの値をキーに対して 1 つずつ出力します。

私はこれを試しましたが、返される文字列のみを取得し、

String key = iterator.next().toString();  
ArrayList<String> value = (ArrayList<String> )test1.get(key)
4

5 に答える 5

153
for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
    String key = entry.getKey();
    ArrayList<String> value = entry.getValue();
    // now work with key and value...
}

ところで、実際には変数をインターフェイス タイプとして宣言する必要がありますMap<String, List<String>>

于 2012-09-07T02:28:10.127 に答える
14

getステートメントにタイプミスがあり、test1.get(key)であると想定しています。もしそうなら、そもそもマップに正しい型を入れていない限り、なぜそれがArrayListを返さないのかわかりません。

これは機能するはずです:

// populate the map
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.put("key1", new ArrayList<String>());
test1.put("key2", new ArrayList<String>());

// loop over the set using an entry set
for( Map.Entry<String,List<String>> entry : test1.entrySet()){
  String key = entry.getKey();
  List<String>value = entry.getValue();
  // ...
}

またはあなたが使用することができます

// second alternative - loop over the keys and get the value per key
for( String key : test1.keySet() ){
  List<String>value = test1.get(key);
  // ...
}

実装を使用して定義する特別な理由がない限り、変数を宣言するとき(および汎用パラメーターで)はインターフェース名を使用する必要があります。

于 2012-09-07T02:32:58.690 に答える
8

エントリ セットを使用してエントリを反復処理することで、キーと値の両方に直接アクセスできます。

for (Entry<String, ArrayList<String>> entry : test1.entrySet()) {
     System.out.println(entry.getKey() + "/" + entry.getValue());
}

私はこれを試しましたが、文字列を返すだけです

どうしてそう思うの?このメソッドは、あなたのケースでは、ジェネリック型パラメーターが選択されたget型を返します。EArrayList<String>

于 2012-09-07T02:28:36.007 に答える
7
// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
    // iterate over each entry
    for(String item : entry.getValue()){
        // print the map's key with each value in the ArrayList
        System.out.println(entry.getKey() + ": " + item);
    }
}
于 2012-09-07T02:28:39.193 に答える