Muu
Muu

Reputation: 31

How do I print a specific number of items in a treemap

I'm trying to print out only 10 values in this treemap, which I filled in from a hashmap.But all the ways I see to traverse the list only allows me to print out all the keys and values and not just 10.

    TreeMap<Integer, String> displayTen = new TreeMap<Integer, String>();

    displayTen.putAll(allValues);

    for (Map.Entry m : displayTen.entrySet()) {
            System.out.println(m.getKey() + " " + m.getValue());
    }

Upvotes: 0

Views: 106

Answers (1)

Amit Kumar Lal
Amit Kumar Lal

Reputation: 5789

int count = 0;
  TreeMap<K,V> resultMap = new TreeMap<K,V>();
  for (Map.Entry<K,V> entry:source.entrySet()) {
     if (count == 10) 
        break;
     resultMap.put(entry.getKey(), entry.getValue());
     count++;
  }
  return resultMap;

Upvotes: 1

Related Questions