google-collections探訪(4) -落穂拾い-

前回:google-collections探訪(3) -Immutableなコレクション- - souta-bot log

BiMap

双方向マップ。
日本語⇔英語みたいに双方向変換Mapに使える。

public static final BiMap<String, String> view = new ImmutableBiMap.Builder<String, String>()
	                                                      .put("USD", "米ドル")
	                                                      .put("EUR", "ユーロ")
	                                                      .put("JPY", "日本円")
	                                                      .put("GBP", "英ポンド")
	                                                      .build();

System.out.println(view.get("USD"));             // 米ドル
System.out.println(view.inverse().get("ユーロ")); // EUR

補助クリエータ

よくJavaの冗長性の例として言及されるコンストラクタでのGenericsの型指定を簡潔にする。

// before
Map<String, List<String>> m1 = new HashMap<String, List<String>>();
// after
Map<String, List<String>> m2 = Maps.newHashMap();

Java7では型推論が改善されてこうなるみたい(Proposal: Improved Type Inference for Generic Instance Creation)

Map<String, List<String>> m3 = new HashMap<>();

Joiner

PythonライクなJoin。

Joiner joiner1 = Joiner.on("; ").skipNulls();
System.out.println(joiner1.join("foo", "bar", null, "baz"));  //foo; bar; baz

Joiner joiner2 = Joiner.on(": ").useForNull("NULL");
System.out.println(joiner2.join("hoge", null, "huga", null)); //hoge: NULL: huga: NULL