Johnny
Johnny

Reputation: 1154

How select first N items in Java TreeMap?

Given this map

SortedMap<Integer, String> myMap = new TreeMap<Integer, String>();

Instead of a for loop is there a utility function to copy first N items to a destination map?

Upvotes: 16

Views: 31936

Answers (5)

Paul
Paul

Reputation: 20061

Using the power of Java 8+:

TreeMap<Integer, String> myNewMap = myMap.entrySet().stream()
    .limit(3)
    .collect(TreeMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), Map::putAll);

Upvotes: 31

Ben
Ben

Reputation: 318

You can also use an ordored iterator to get the first x records, orderer by descending id for instance :

Iterator<Integer> iterator = myMap.descendingKeySet().iterator();

Upvotes: 1

Andreas Dolk
Andreas Dolk

Reputation: 114787

Maybe, but not as part of the standard Java API. And: the utility would use a loop inside.

So you'll need a loop, but you can create your own "utility" by doing it all in a static method in a utility class:

public static SortedMap<K,V> putFirstEntries(int max, SortedMap<K,V> source) {
  int count = 0;
  TreeMap<K,V> target = new TreeMap<K,V>();
  for (Map.Entry<K,V> entry:source.entrySet()) {
     if (count >= max) break;

     target.put(entry.getKey(), entry.getValue());
     count++;
  }
  return target;
}

The complexity is still O(n) (I doubt, that one can achieve O(1)) but you use it like a tool without "seeing" the loop:

SortedMap<Integer, String> firstFive = Util.putFirstEntries(5, sourceMap);

Upvotes: 8

WhiteFang34
WhiteFang34

Reputation: 72049

There's SortedMap.headMap() however you'd have to pass a key for the element to go up to. You could iterate N elements over Map.keySet() to find it, e.g.:

Integer toKey = null;
int i = 0;
for (Integer key : myMap.keySet()) {
    if (i++ == N) {
        toKey = key;
        break;
    }
}

// be careful that toKey isn't null because N is < 0 or >= myMap.size()
SortedMap<Integer, String> copyMap = myMap.headMap(toKey);

Upvotes: 7

Ammu
Ammu

Reputation: 5127

You can use the putAll(Map t) function to copy the items from the map to specified map.But it copies all the items. You cannot copy fixed number of items.

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html#putAll%28java.util.Map%29

Upvotes: -1

Related Questions