如何遍历TreeMap的PORTION?

时间:2012-04-21 22:33:46

标签: iteration treemap alphabetical

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

2 个答案:

答案 0 :(得分:1)

使用TreeMap的subMap()方法获取仅包含要检查的键范围的SortedMap。然后遍历该SortedMap。

答案 1 :(得分: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 =&gt; ABB 18 =&gt; DEF