How to select the first n items in Java treemap?

Given this map

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

Instead of the for loop, is there a utility function to copy the first n items to the target map?

Solution

Maybe, but not part of the standard Java API And: the utility will use a loop

So you need a loop, but you can create your own "utility" 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 suspect o (1) can be implemented), but you can use it like a tool without seeing a loop:

SortedMap<Integer,String> firstFive = Util.putFirstEntries(5,sourceMap);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>