什么是番石榴中的 SingletonImmutableBiMap

what is SingletonImmutableBiMap from guava

我的问题很简单。 guava 中的 SingletonImmutableBiMap 是什么,为什么它包含 singletonbi 等关键字?

ImmutableMap 的意思很清楚,但其他两个关键字的目的是什么?

我们什么时候使用这个实现?我通过调用

注意到了这个 class

.stream().collect(ImmutableMap.toImmutableMap(ConfigItem::getId, Function.identity()))

Singleton:仅包含 1 个元素。对于 immutable 集合,它们的大小不会改变,因此您可以为空集合、单元素集合或其他小型集合分别实现。它很有用,因为它们比一般实现需要更少的内存并且可以更快地执行。例如。对于 EmptyMap contains 方法可以只是 return false 而不是复杂的哈希-table 查找逻辑。

Bi:双向,既可以按值取键,也可以按键取值。参见 https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/BiMap.html

When shall we use this implementation?

从不,因为它不是 public。它的存在是一个内部细节。

此处实际使用的 class 是一个实现细节,您不必担心。

SingletonImmutableBiMap it's an instance of ImmutableMap created when you collect stream containing one element. The map in this case is also a BiMap,因为所有键和值都是唯一的。 Guava 通过对 MapBiMap 情况重新使用 SingletonImmutableBiMap 来优化总 class 计数。

编辑:

顺便说一句,您可能可以在此处使用 Maps.uniqueIndex

Map<Integer, ConfigItem> m = Maps.uniqueIndex(configItems, ConfigItem::getId);