假设我有一个像这样的 HashMap:
message.put(10, "Message 1");
message.put(20, "Message 2");
message.put(30, "Message 3");
message.put(40, "Message 4");
我会收到一条比较给定 ID 的消息:
if( message.containsKey(sampleValue) ) {
return message.get(sampleValue);
}
但是,如果 sampleValue 未包含在 message HashMap 中,那么这是没有用的。有没有办法或者函数可以通过大概的ID值来获取它?例如,如果sampleValue是19,它将返回“Message 2”。我怎样才能实现这个目标?
最佳答案
您可以使用 TreeMap
来完成您的任务。它包含从右/左返回最近的键的 ceilingKey
/floorKey
方法。因此,这些方法可用于查找最接近的键并在 O(Log(N))
中检索其对应的值。
class ClosestKeyTreeMap extends TreeMap<Integer, Object> {
public Object getClosestValue(int key) {
Integer leftKey = this.floorKey(key);
Integer rightKey = this.ceilingKey(key);
if (leftKey == null && rightKey == null) {
return null;
} else if (rightKey == null) {
return this.get(leftKey);
} else if (leftKey == null) {
return this.get(rightKey);
}
int leftDiff = key - leftKey;
int rightDiff = rightKey - key;
if (leftDiff < rightDiff) {
return this.get(leftKey);
} else {
return this.get(rightKey);
}
}
}
关于java - 通过近似 ID 值(不相同)从 hashmap 获取消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50842015/