Forum Stats

  • 3,826,778 Users
  • 2,260,707 Discussions
  • 7,897,072 Comments

Discussions

Retrieve last element in the Map

User_19BPU
User_19BPU Member Posts: 1,086 Blue Ribbon
edited Apr 18, 2017 9:54PM in Java Programming

Hi,

  I have Map which contains 5 elements, I want to iterate retrieve only the last element in the Map, how I can get the last element in the loop?

Thanks

rpc1eudriscabrera-JavaNetTPD-Opitzjwenting

Answers

  • Unknown
    edited Jan 7, 2017 11:43AM
    I have Map which contains 5 elements, I want to iterate retrieve only the last element in the Map, how I can get the last element in the loop?

    What was YOUR answer to that interview question? Did they say you were right? Post the answer you gave and tell us all about the interview: the types of questions ask, the responses you got, etc.

    I would have simply ask them: what does 'last element' mean to you?

    And then told them that 'Map' is an interface - most implementations do NOT guarantee any order at all for either the keys or the values.

    1. use 'entrySet' to get the 'Set' of the values - then use 'iterator' to to get one and iterate to the end or use 'toArray' and then access the last element of the array

    2. use 'keySet' to get the 'Set' of the keys - then use 'iterator' iterate to get one and iterate to the end of the keys and then use that key to get the corresponding value. Or use 'toArray', access the last element of the array and use that key to get the corresponding map value.

    3. use 'values' to get the 'Collection' of the values - then do the same as #1 above

    But, generally speaking, a 'Map' does NOT have a first or last element.

    rpc1eudriscabrera-JavaNetTPD-Opitzjwenting
  • Vinod Kumar Kashyap
    Vinod Kumar Kashyap Member Posts: 38
    edited Mar 31, 2017 10:59AM

    You can use TreeMap and its method lastKey()

  • jwenting
    jwenting Member Posts: 4,864 Gold Badge
    edited Apr 4, 2017 2:20AM

    A TreeMap is a Map representation of a Tree, not an actual Map...

  • dvohra21
    dvohra21 Member Posts: 14,576 Gold Crown
    edited Apr 18, 2017 9:54PM

    Sorting is provided by SortedMap<K,V> in which the lastKey() method returns the last (highest) key currently in the map.

This discussion has been closed.