Question

I have the following BiMap collections:

BiMap<String,String> accessIds = HashBiMap.create();
accessIds.put("FOO","accessId 1"); //This access Id is common to both FOO and BAR

BiMap<String,String> merchants = HashBiMap.create();
merchants.put("FOO", "merchant 1"); //Both FOO and BAR each have unique merchants
merchants.put("BAR", "merchant 2");

These are 2 of the 4 total collections I currently have. All 4 collections share the same keys, but different values.

The question I have is: How can I ensure that I can get merchant 2 when I have an accessIds key of FOO?

Before someone points out that these two collections do not, in fact, share the same keys, please remember that a BiMap enforces unique values so I am unable to list "BAR","accessId 1" in the collection.

I'm not convinced that BiMap is the right collection, but I do make use of its inverse() method. If there is a collection better suited ( or some other method that I am overlooking ) please let me know.

FYI: I use Guava-14.0-rc1 for the BiMap collection.

Was it helpful?

Solution

Based on your comment, in your workflow, the Access ID is a key, not a value, that in at least one case has several associated values instead of one.

You could use a Multimap for your Access IDS, assuming you can then select which value to retain as the key for accessing the other Maps (or BiMaps, though it's unclear through your example why they are BiMaps, but I guess that's unrelated).

ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();
builder.put("FOO", "accessId 1");
builder.put("BAR", "accessId 1");
ImmutableMultimap<String, String> accessIds = builder.build();
ImmutableMultimap<String, String> byAccessIds = accessIds.inverse();

Collection<String> keys = byAccessIds.get("accessId 1"); // ["FOO", "BAR"]
String key = doSomething(keys); // "BAR" is chosen
String merchant = merchants.get(key); // "merchant 2"

If you cannot use immutable structures, you can also build a regular Multimap for accessIds (for example using a HashMultimap) and inverse it using Multimaps.invertFrom().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top