简体   繁体   中英

Hashtable - Get the 1st element before index

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?

NavigableMap (as mentioned in comment by user15358848)

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.

lowerEntry

Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.

  1. get value for key
  2. if fetched value is null , then fetch lowerEntry
  3. 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;

floorEntry

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.

  1. read using floorEntry
  2. if non-null entry, return value
  3. else return 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM