BiMap

Introduction

We know that Guava provides a special Map structure called BiMap, which implements a bidirectional lookup function, that is, looking up value by key and looking up key by value. Hutool also provides this object.

BiMap requires that both keys and values must be unique (not强制性required). If a key is duplicated, the later key-value pair will overwrite the previous one. If a value is duplicated, it will overwrite the key in an unspecified order, which depends entirely on the Map implementation. For example, if HashMap is unordered (in hash order), then which one overwrites the other is related to the hash algorithm; if it is LinkedHashMap, it is ordered, and the later one overwrites the earlier one.

Usage

BiMap<String, Integer> biMap = new BiMap<>(new HashMap<>());
biMap.put("aaa", 111);
biMap.put("bbb", 222);

// 111
biMap.get("aaa");
// 222
biMap.get("bbb");

// aaa
biMap.getKey(111);
// bbb
biMap.getKey(222);