I have this hashtable:
private final Hashtable<Integer,Character> htable = new Hashtable<>();
I am storing some element in the table with indexes that may reach high ranges. Then when i want to get an item, if it does not exist, i would like the get the first existing one before.
A naive way to do it could be:
int index = given_index;
while(htable.get(index) == null && index >= 0)
index --;
Doing this may compute a big amount of values. Is there a better strategy, or maybe another sort of table allowing to compute less?
Ref: NavigableMap
Generally, implementations should not support null
values. If there are implementations that supports null
, it will be impossible to check whether the response null
was due to absence or an actual value.
Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
get
value for key null
, then fetch lowerEntry
getOrDefault(key, navigableMap.lowerEntry(index))
will be costly if actual key is present mostly due to additional navigableMap.lowerEntry
call Character value = navigableMap.get(index);
if (value == null) {
value = navigableMap.lowerEntry(index);
}
return value;
Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.
floorEntry
null
Map.Entry<Integer, Character> entry = navigableMap.floorEntry(index);
return null != entry ? entry.getValue() : null;
get the index or the index in front of it with a lambda
htable.keySet().stream().sorted()
.filter(i -> i <= target).max(Integer::compare).orElse(-1);
… where target
is the index You are searching
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.