Question

If I have a treemap that contains string and double. Is there anyway to retrieve say first 10 keys from map?

Was it helpful?

Solution

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());
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top