Comparing existing data records in Java

I have a HashMap associated key to strings and I need to compare some strings to each other. However, some of the lines may or may not be in the HashMap.

Example. Let's say I have 4 lines that I plan to compare against each other if possible, but only 3 of them end up in the HashMap. How can I compare strings that are present without trying to compare them to a string that is not, and does a bunch of nested ifs and elses?

edit: Alohci's solution was simple and quick and it worked.

+1


source to share


2 answers


Loop through the .valash HashMap collection. Save the first entry. Compare each remaining record with the saved one. Once you find one that doesn't match, throw your mistake. If you reach the end of the loop, then all lines match.



+2


source


It sounds like you need a reverse mapping that maps all values ​​to their keyset.

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

      



Then you can see if all the records you are looking for are in the set. Make sure you add inverse mapping when adding / removing forward mapping.

The advantage of this approach is that the test will be O (n), where n is the size of the keys being tested, not O (m), where m is the size of the straight map.

0


source







All Articles