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}
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}
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;
}
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
).
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.
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)
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.
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..