Reputation: 1857
How to check if a value exists in between a key and its value in hash table?
I want to check if a value is present in hash table or in between any of the key and its value
I used the following code to check if a value is present as a key or value
if(table.containsKey(val) || table.containsValue(val))
But how to check if it is present in between any of the key and its corresponding value?
Upvotes: 1
Views: 1326
Reputation: 636
This also works:
public static <T extends Comparable> boolean hasValueBetween(Map<T, T> map, T value) {
for(Map.Entry<T, T> entry : map.entrySet()) {
if (entry.getKey().compareTo(value) <= 0 && entry.getValue().compareTo(value) >= 0) {
return true;
}
}
return false;
}
Upvotes: 0
Reputation: 8466
Try this,
Upvotes: 0
Reputation: 328568
So basically you want to flatten out the map and check if a given value is contained in the range between the lowest key or value and the largest key or value.
You could put all the keys and values in a SortedSet
, for example a TreeSet
, which has the first()
and last()
methods to retrieve the lowest / highest item.
It could look like this:
SortedSet<Integer> set = new TreeSet<> ();
set.addAll(map.keySet());
set.addAll(map.values());
//return true if input within the range
return (input >= set.first() || input <= set.last());
You could populate the set in parallel with the map for efficiency to avoid recreating a set for every query.
Upvotes: 1