0

我正在做一个作业,我必须搜索 TreeMap 中的键(映射到它们所在的文件。基本上,这个 TreeMap 是一个倒排索引),它以我们在程序中指定的查询词开头一个查询文件。但是,为了提高效率,我的教授不希望在我们查找以查询词开头的键时遍历 TreeMap 中的所有键,而是希望我们只遍历需要遍历的键。例如,如果查询词以 C 开头,那么我们应该只遍历以 C 开头的键。关于如何处理这个问题的任何想法?

4

2 回答 2

1

使用 TreeMap 的subMap()方法获得一个 SortedMap,它只包含您要检查的键范围。然后迭代该 SortedMap。

于 2012-04-22T00:49:55.710 回答
0

这是@ottomeister 建议的基本实现:

public class Tester{
    public static void main(String a[]){
        TreeMap<CustomObject,String> tm = new TreeMap<CustomObject,String>();
        tm.put(new CustomObject(4,"abc"),"abc");
        tm.put(new CustomObject(7,"bcd"),"bcd");
        tm.put(new CustomObject(25,"cde"),"cde");
        tm.put(new CustomObject(18,"def"),"def");
        tm.put(new CustomObject(2,"efg"),"efg");
        tm.put(new CustomObject(8,"fgh"),"fgh");
        tm.put(new CustomObject(3,"aab"),"aab");
        tm.put(new CustomObject(13,"aab"),"abb");

        Map<CustomObject, String> sub = tm.subMap(new CustomObject(9,""),new CustomObject(20,""));

        for(Map.Entry<CustomObject,String> entry : sub.entrySet()) {
            CustomObject key = entry.getKey();
            String value = entry.getValue();

            System.out.println(key.getId() + " => " + value);
        }
    }
}

class CustomObject implements Comparable<CustomObject>{
    private int id;
    private String Name;
    CustomObject(int id, String Name){
        this.id = id;
        this.Name = Name;
    }
    @Override
    public int compareTo(@NotNull CustomObject o) {
        return this.id - o.id;
    }
    public int getId(){
        return this.id;
    }
}

输出:13 => abb 18 => def

于 2018-01-03T10:14:38.010 回答