0

その中にハッシュマップと値があります。ここで、マップ内の値をキーとして、キーを値として設定したいと考えています。誰でもアイデアを提案できますか?

マイマップは

Map<String, String> col=new HashMap<String, String>();
col.put("one","four");
col.put("two","five");
col.put("three","Six");

ここで、別のマップを作成し、上記のように別の方法で配置したいと思います。つまり、

Map<String, String> col2=new HashMap<String, String>();
col.put("five","one");
col.put("four","two");
col.put("Six","three");

誰でもアイデアがありますか?ありがとう

4

3 に答える 3

2

そのようです:

Map<String, String> col2 = new HashMap<String, String>();
for (Map.Entry<String, String> e : col.entrySet()) {
    col2.put(e.getValue(), e.getKey());
}
于 2013-03-11T11:38:05.667 に答える
1

値がハッシュマップで一意であると仮定すると、次のようにすることができます。

// Get the value collection from the old HashMap
Collection<String> valueCollection = col.values();
Iterator<String> valueIterator = valueCollection.iterator();
HashMap<String, String> col1 = new HashMap<String, String>();
while(valueIterator.hasNext()){
     String currentValue = valueIterator.next();
     // Find the value in old HashMap
     Iterator<String> keyIterator = col.keySet().iterator();
     while(keyIterator.hasNext()){
          String currentKey = keyIterator.next();
          if (col.get(currentKey).equals(currentValue)){
               // When found, put the value and key combination in new HashMap
               col1.put(currentValue, currentKey);
               break;
          }
     }
}
于 2013-03-11T10:48:34.713 に答える
0

別のものを作成しMap、キー/値を 1 つずつ反復処理して、 new に入れMapます。最後に古いものを削除します。

于 2013-03-11T10:53:37.277 に答える