如何遍历TreeMap的PORTION?

问题描述 投票:0回答:2

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

iteration treemap alphabetical
2个回答
1
投票

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


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

© www.soinside.com 2019 - 2024. All rights reserved.