开发者

Iterating a treemap for fixed number of times

开发者 https://www.devze.com 2023-02-03 09:32 出处:网络
If I have a tree开发者_开发知识库map that contains string and double. Is there anyway to retrieve say first 10 keys from map?Fetch the iterator via treeMap.entrySet().iterator() if you want the key/va

If I have a tree开发者_开发知识库map that contains string and double. Is there anyway to retrieve say first 10 keys from map?


Fetch the iterator via treeMap.entrySet().iterator() if you want the key/value pairs or treeMap.keySet().iterator() if you just care about the keys, then call iterator.next() 10 times or as long as iterator.hasNext() returns true.

List<Map.Entry<String, Double>> firstTen = new ArrayList<Map.Entry<String, Double>>(10);
Iterator<String, Double> iterator = treeMap.entrySet().iterator();
for (int i = 0; iterator.hasNext() && i < 10; i++) {
    firstTen.add(iterator.next());
}


Not in the JDK but there are methods in 3rd-party libraries that do this.

For example Iterables.limit from guava


Since a TreeMap is a NavigableMap, you should take a look at the methods in that interface. There's nothing that lets you select the first n, but you can select all entries with a key less than a given key, etc.

Otherwise, I would just use an Iterator and stop after n iterations.


Wrap the entrySet() in a List and create a subList():

SortedMap<String,Double> treeMap = new TreeMap<String, Double>();
List<Entry<String, Double>> firstTen = 
    new ArrayList<Map.Entry<String,Double>>(treeMap.entrySet())
    .subList(0, 10);
for(Entry<String, Double> entry : firstTen){
    // do something with entries
}

Drawback: the entire map will be copied to the list.


It worked with the code snippets provided by dkarp and sean. However, it worked with the suggestion of DJClayworth as well. Here is how I solved it:

    c=sorted_map.keySet();

    Iterator itr=c.iterator();
    String s="";
    while (i<iteratesize&&itr.hasNext()){
        s=(String) itr.next();
        System.out.println(s);
        s="";
        i++;
    }

Thank you very much everyone for your help. I really appreciate it.

0

精彩评论

暂无评论...
验证码 换一张
取 消