我沿着由 LinkedHashMap<Foo, Double>
表示的线设置了一系列对象其中第一个字段是对象,第二个字段是它与测量原点的距离。我知道元素是按增加的距离排序的。我希望能够选择一些位置 x
并在左侧和右侧搜索 Foo
的实例其中 foo.isInteresting()
返回 true
无需遍历整个 map 。
我的第一个想法是做这样的事情:
- 遍历所有条目以找到距离大于
x
的第一个条目 - 从这一点开始向左查看所有条目,直到
foo.isInteresting()
。 - 从这一点开始查看所有条目直到
foo.isInteresting()
但据我所知,没有办法遍历 Map
从某个起点。创建两个 List
是否明智?我 map 上的对象并使用 ListIterator
?
因为我需要通过 Foo
进行搜索,所以交换键和值也不是完全明智的在我的应用程序的其他地方。
最佳答案
您可以使用 TreeSet<Foo>
,在里面保持距离Foo
并准备一个比较器。也可以创建一个包含Foo和distance且具有可比性的wrapper对象,保存在TreeSet<Wrapper>
中.然后你可以使用lower
和 higher
NavigableSet
的方法.
class Wrapper implements Comparable<Wrapper> {
public Foo foo;
public Double distance;
public Wrapper(Foo foo, Double distance) {
this.foo = foo;
this.distance = distance;
}
/**
* Use only Foo for hashcode and equals
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((foo == null) ? 0 : foo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Wrapper other = (Wrapper) obj;
if (foo == null) {
if (other.foo != null)
return false;
} else if (!foo.equals(other.foo))
return false;
return true;
}
@Override
public int compareTo(Wrapper o) {
return distance.compareTo(o.distance);
}
}@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Wrapper other = (Wrapper) obj;
if (foo == null) {
if (other.foo != null)
return false;
} else if (!foo.equals(other.foo))
return false;
return true;
}
@Override
public int compareTo(Wrapper o) {
return distance.compareTo(o.distance);
}
}
这让您可以按 Foo 搜索并按距离排序。
关于java - 如何在 map 中找到一个点并左右搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11670892/