Last active
September 29, 2016 15:24
-
-
Save kuneo/3843f1a9f9f73e8f7f00c6593bd67b38 to your computer and use it in GitHub Desktop.
apache commonsのBidiMap(双方向マップ)の使い方
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 通常のマップを生成 | |
Map<String, Integer> map = new HashMap<>(); | |
map.put("suzuki", 1); | |
map.put("tanaka", 2); | |
// 生成した通常のマップを双方向マップに挿入 | |
BidiMap<String, Integer> bidiMap = new DualHashBidiMap<>(map); | |
// getKey()でvalueからkeyを取得できる | |
System.out.println(bidiMap.getKey(1)); | |
// 当然、get()でkeyからvalueも取得できる | |
System.out.println(bidiMap.get("suzuki")); | |
System.out.println("--- 要素を追加して拡張for文を回してみる ---"); | |
bidiMap.put("sato", 3); | |
// 双方向マップは、keyだけでなくvalueも一意となる | |
// 下記のように重複するvalueを追加すると、上書きされることに注意 | |
bidiMap.put("yamada", 2); | |
for(Map.Entry<String, Integer> entry : bidiMap.entrySet()) { | |
System.out.println("key:" + entry.getKey()); | |
System.out.println("value:" + entry.getValue()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment