My question is simple. What is SingletonImmutableBiMap from guava and why it contains keywords like singleton and bi?
It's very clear what an ImmutableMap means but what is the purpose of the other two keywords?
When shall we use this implementation? I noticed this class by calling
.stream().collect(ImmutableMap.toImmutableMap(ConfigItem::getId, Function.identity()))
Singleton: contains just 1 element. For immutable collections, their size doesn't change and so you can have separate implementations for empty, single-element or otherwise small collections. It's useful because they need a lot less memory than general implementations and can perform faster. E.g. for an EmptyMap contains method can be just return false instead of complex hash-table lookup logic.
Bi: bidirectional, i.e. you can get key by values as well as value by key. See https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/BiMap.html.
When shall we use this implementation?
Never, because it isn't public. Its existence is an internal detail.
Actual class used here is an implementation detail and you should not be worried about it.
SingletonImmutableBiMap it's an instance of ImmutableMap created when you collect stream containing one element. The map in this case is also a BiMap, since both all key(s) and value(s) are unique. Guava optimizes total class count by re-using SingletonImmutableBiMap for both Map and BiMap case.
EDIT:
BTW You probably can use Maps.uniqueIndex here:
Map<Integer, ConfigItem> m = Maps.uniqueIndex(configItems, ConfigItem::getId);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With