java - 如何在 map 中找到一个点并左右搜索

标签 java search dictionary iterator

我沿着由 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>中.然后你可以使用lowerhigher 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/

相关文章:

algorithm - 是否可以使用搜索功能枚举集合中的所有项目

C++ 字计数器

java - EJB 警告 : WELD-000411: . .. 考虑使用 @WithAnnotations 或具有边界的通用类型来限制事件

java - 如何在 Android 中处理 <br/> 标签

java - 从 ByteBuffer/Netty ByteBuff 并行/多线程读取

python - Pandas Dataframe 中的频率词典

javascript - amCharts 4 中 mapImage 上的单击事件

java - 从 servlet 中获取对象的数组列表

search - ElasticSearch中 token 过滤器的控制顺序

php - 将输入查询添加到搜索功能 Laravel Scout 的路由值