1

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?

4

3 回答 3

1

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.

于 2013-06-28T08:36:01.823 回答
0

Try this,

  1. Iterate the HashTable
  2. store the key and value in diff temp
  3. Then compare the value in between the tempkey and tempvalue
于 2013-06-28T08:38:30.520 回答
0

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;
}
于 2013-06-28T09:00:15.687 回答