Created
May 7, 2013 08:17
-
-
Save YukiYoshikawa/5531035 to your computer and use it in GitHub Desktop.
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
package trial.yy.guava.client.collect; | |
import com.google.common.collect.BiMap; | |
import com.google.common.collect.HashBiMap; | |
import java.util.Set; | |
/** | |
* com.google.common.collect.BiMapを試すためのサンプル | |
* User: yy | |
*/ | |
public class BiMapClient { | |
public static void main(String[] args) { | |
BiMap<Integer, String> map = HashBiMap.create(); | |
map.put(1, "Koizumi"); | |
map.put(2, "Abe"); | |
map.put(3, "Aso"); | |
map.put(4, "Hatoyama"); | |
map.put(5, "Kan"); | |
// keyからvalueの取得(普通のMapと同じ操作) | |
System.out.println("### BiMap#get"); | |
String value1 = map.get(1); | |
String value2 = map.get(3); | |
System.out.println("key: " + 1 + " -> value: " + value1); | |
System.out.println("key: " + 3 + " -> value: " + value2); | |
// valueからkeyを取得してみる(inverseでkeyとvalueを逆転させたBiMapに対してgetを実行) | |
System.out.println("### BiMap#inverse"); | |
int key1 = map.inverse().get("Abe"); | |
int key2 = map.inverse().get("Hatoyama"); | |
System.out.println("value: Abe -> key: " + key1); | |
System.out.println("value: Hatoyama -> key: " + key2); | |
// 既に登録済みのvalueを再度BiMap#putで登録するとIllegalArgumentExceptionがスローされる | |
System.out.println("### BiMap#put"); | |
try { | |
map.put(6, "Koizumi"); | |
} catch (IllegalArgumentException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("key: " + 6 + " -> value: " + map.get(6)); | |
// 既に登録済みのvalueでもBiMap#forcePutを使うと登録可能 | |
// 元々登録済みだったvalueとkeyの組合せの要素は削除される | |
System.out.println("### BiMap#forcePut"); | |
try { | |
map.forcePut(6, "Koizumi"); | |
} catch (IllegalArgumentException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("key: " + 1 + " -> value: " + map.get(1)); | |
System.out.println("key: " + 6 + " -> value: " + map.get(6)); | |
// BiMapはvalueも一意なのでvaluseメソッドで値のSetを取得することができる | |
System.out.println("### BiMap#values"); | |
Set<String> valuseSet = map.values(); | |
System.out.println("values: " + valuseSet); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment