tags:

views:

202

answers:

2

I have a HashMap relating Keys to Strings, and I need to compare some of the Strings against each other. However, some of the Strings may or may not be in the HashMap.

Example: Let's say I have 4 Strings that I plan to compare to each other if possible, but only 3 of them end up in the HashMap. How can I compare the Strings that are present without trying to compare them to the String that isn't, and without doing a bunch of nested ifs and elses?

edit: Alohci's solution was easy and fast, and it worked.

+2  A: 

Loop through the .values collection of the HashMap Store the first entry. Compare each remaining entry with the stored one. As soon as you find one that doesn't match, throw your error. If you reach the end of the loop then all the strings match.

Alohci
Thanks! I should have thought of that earlier.
Blue
Good way to get all the values stored in a HashMap collection in a list rather than iterating through a keyset.
Tushu
A: 

It sounds like you need a reverse mapping, that maps all the values to their set of keys.

Map<Key,Value> forwardMap;
Map<Value, Set<Key> reverseMap;

You can then see if all of the entries you are looking at are in the set. Make sure that you put the reverse mapping in when you add/remove the forward mapping.

The benefit of this approach, is the test will be O(n) where n is the size of the keys you are testing, and not O(m) where m is the size of the forward map.

Milhous