0

How to get value of last HashMap key?

Map<Integer, Employee> map = new HashMap<Integer, Employee>();
map.put(1, "FIRST INSERTED");
map.put(2, "SECOND INSERTED");
map.put(3,"THIRD INSERTED");

What I want to do is take value of last key (3), increment it and add another row with next number (4).

justcurious
  • 839
  • 3
  • 12
  • 29
Dorota
  • 40
  • 1
  • 3
  • 1
    Iterate till last. and then add. But HashMap doesn't guarantee same order of insertion while iterating over it – SacJn Oct 23 '15 at 10:50

3 Answers3

3

Maps don't have a last entry, it's not part of their contract.

Neither HashMap maintains insertion order.

Try using SortedMap, NavigableMap, and access the last entry

    NavigableMap<String,Integer> map = new TreeMap<String, Integer>();
    map.lastEntry().getKey()

There is also LinkedHashMap that maintains the order in which keys are inserted. There is however no interface to back up this functionality, nor is there a direct way to access the last key.

PS : Read this

Community
  • 1
  • 1
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
1

You can't use a normal HashMap for that, you need another member of the "collections" family; in thise case, its cousin LinkedHashMap. That one keeps the order in which elements were added. Keep in mind that those two different maps do show different behavior regarding "cost" of insert/delete/iterating operations.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

A HashMap does not guarantee any order. If by "last key" you mean "max key", you should rather find maximum of the Set<Integer> returned by map.keySet().

OR use another type of Map (NavigableMap for example) as suggested by other answers.

Gaël J
  • 11,274
  • 4
  • 17
  • 32