Search code examples
javaiterationtreemap

Iterating a treemap for fixed number of times


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


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