如何遍历TreeMap的PORTION?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何遍历TreeMap的PORTION?相关的知识,希望对你有一定的参考价值。
我正在进行一项任务,我必须搜索TreeMap中的键(映射到它们所在的文件。基本上,这个TreeMap是一个倒置索引),它以我们在程序中指定的查询字开头。一个查询文件。但是,为了提高效率,我的教授不希望在查找以查询词开头的键时迭代TreeMap中的所有键,而是希望我们只迭代我们需要迭代的键。例如,如果查询单词以C开头,那么我们应该只遍历以C开头的键。有关如何处理这个问题的想法吗?
答案
使用TreeMap的subMap()
方法获取一个SortedMap,它只包含您要检查的键范围。然后遍历该SortedMap。
另一答案
以下是@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
以上是关于如何遍历TreeMap的PORTION?的主要内容,如果未能解决你的问题,请参考以下文章