Amrmsmb
Amrmsmb

Reputation: 11406

How to return last added value from the HashMap

I am trying to write a generic function that return the last added value in a hashmap. i created the same method for the ArrayList but i do not know how to do it for the HashMap

public <T><T> T lastAddedObj(HashMap<Integer, T> list) {
        // TODO Auto-generated method stub
        if (list != null) {
            if (!list.isEmpty()) {
                return list.get(( list.size() - 1) );
            } else {
                Log.E(TAG, "lastAddedObj", "the generic object list received is empty!!");
                return null;
            }
        } else {
            Log.E(TAG, "lastAddedObj", "the generic object list received is null!!");
            return null;
        }
    }

Upvotes: 0

Views: 1696

Answers (2)

Akshay Shinde
Akshay Shinde

Reputation: 947

maybe you can use Arraylist for getting last value.

something like,

List<String> list = new ArrayList<>();

then after adding the items you can get its size,

int size = list.size();

and then to get last item,

String last_item = list.get(size - 1);

Upvotes: 1

MadConan
MadConan

Reputation: 3767

There is no direct way to do what you want. Map is an unordered construct. However, there are some options:

  • Keep a reference to the last item added somewhere
  • Create your own key type that includes information about when the key was added. This would require looping over the key set to see which key was added after some time/value.
  • Since you are using integers as a key, without knowing anything else, you could add items by using an incremented variable. Then you're back to the same situation as with the second bullet point.

Upvotes: 2

Related Questions