1

How can i get the last and first key/value of a Map? For example:

Map<String,Integer> ret = new HashMap<String,Integer>();

And this is ret's value:

{33=1, 12=2, 21=2, 93=2, 48=9, 68=10}
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
user1024858
  • 129
  • 3
  • 5
  • 11

6 Answers6

4

You cannot do it with HashMap because keys are not ordered. Consider using LinkedHashMap

You can get last element using this method:

public <K,V> Map.Entry<K,V> getLast(LinkedHashMap<K,V> map) {
    Iterator<Map.Entry<K,V>> iterator = map.entrySet().iterator();
    Map.Entry<K, V> result = null;
    while (iterator.hasNext()) {
        result = iterator.next();
    }
    return result;
}
Mairbek Khadikov
  • 7,939
  • 3
  • 35
  • 51
4

A HashMap is an unordered map, so it doesn't have any concept of 'first' or 'last.
If you want a map that retains things in insertion order, you can use a LinkedHashMap, and then iterate its entrySet() method to pick the first and last values.
You could also use the SortedMap interface (TreeMap impl.) which orders inserted entries by the natural ordering of keys (or a provided Comparator).

Mairbek Khadikov
  • 7,939
  • 3
  • 35
  • 51
tzaman
  • 46,925
  • 11
  • 90
  • 115
2

It isn't possible (or more like doesn't make sense) to differentiate between "first" and "last" when it comes to HashMap. If you want to preserve insertion order, you might want to use LinkedHashMap<K,V>. But then again, you should elaborate your question to let us know the exact use case demanding this.

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
1

since there is no defined order you will basically get a random element if you are unlucky.

else you could go the way HashMap -> getEntrySet -> toArray -> get(size-1)

light_303
  • 2,101
  • 2
  • 18
  • 35
1

Technically, you can get the first object from the map via:

Map.Entry<Integer,Integer> entry = map.entrySet().iterator().next();

And the last via:

Iterator<Map.Entry<Integer,Integer>> iter = map.entrySet().iterator();
Map.Entry<Integer,Integer> entry = null;
while(iter.hasNext()) {
    entry = iter.next();
}
// now you have the "last" item in the map stored in 'entry'

But, as has been stated in other answers, this doesn't mean anything with a HashMap. Substitute it with a LinkedHashMap, however, and you can get the first and last inserted pairs out using the above code.

sarumont
  • 1,734
  • 12
  • 11
0

Unless you use a http://docs.oracle.com/javase/6/docs/api/java/util/SortedMap.html, in which case you could get the first and last key..

quaylar
  • 2,617
  • 1
  • 17
  • 31