Skip to content

Instantly share code, notes, and snippets.

@kuneo
Last active September 29, 2016 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuneo/3843f1a9f9f73e8f7f00c6593bd67b38 to your computer and use it in GitHub Desktop.
Save kuneo/3843f1a9f9f73e8f7f00c6593bd67b38 to your computer and use it in GitHub Desktop.
apache commonsのBidiMap(双方向マップ)の使い方
// 通常のマップを生成
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