3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaの双方向mapのライブラリ

Posted at

mapをkey・value双方向から参照したい場合に以下のライブラリが使える。

GuavaのBiMap

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>22.0</version>
</dependency>
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

Map<String, String> m = new HashMap<>();
m.put("a", "あ");
m.put("i", "い");
m.put("u", "う");

BiMap<String, String> bimap = HashBiMap.create(m);
System.out.println(bimap.get("a"));//あ
System.out.println(bimap.inverse().get("あ"));//a

Apache Commons CollectionsのBidiMap

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.1</version>
</dependency>
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;

BidiMap<String, String> bidimap = new DualHashBidiMap<>(m);
System.out.println(bidimap.get("a"));//あ
System.out.println(bidimap.inverseBidiMap().get("あ"));//a
3
5
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?