Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How select first N items in Java TreeMap?

Tags:

java

map

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?

like image 642
Johnny Avatar asked Apr 13 '11 11:04

Johnny


People also ask

How do I sort keys in TreeMap?

To sort keys in TreeMap by using a comparator with user-defined objects in Java we have to create a class that implements the Comparator interface to override the compare method. In the below code, we are passing a custom object as a key in TreeMap i.e Student user-defined class.

How do I get the first item in TreeMap?

Use the firstEntry() method in TreeMap to retrieve the first entry.

Can we sort TreeMap by values in Java?

You can't have the TreeMap itself sort on the values, since that defies the SortedMap specification: A Map that further provides a total ordering on its keys. However, using an external collection, you can always sort Map.

How is sorting done in TreeMap?

In Java Language, a TreeMap always stores key-value pairs which are in sorted order on the basis of the key. TreeMap implements the NavigableMap interface and extends AbstractMap class. TreeMap contains unique keys. The elements in TreeMap are sorted on the basis of keys.


2 Answers

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);
like image 82
Paul Avatar answered Sep 18 '22 05:09

Paul


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);
like image 44
Andreas Dolk Avatar answered Sep 18 '22 05:09

Andreas Dolk