javaarraylisthashmaplinkedhashmapkeyset

How to access to a hashmap keyset with arraylist


Actually, I create a new ArrayList of keyset of a LinkedHashMap every time I want the position of a key.

public static Map<Integer, Object> ObjectsWithId = new LinkedHashMap<>();


public int getId(int number) {
     return (number <= ObjectsWithId.size()) ? new ArrayList<Integer>(ObjectsWithId.keySet()).get(number-1) : -1;
}

Is there a way to create a "link" of HashMap's keyset with an ArrayList ? I would want to don't have to create an ArrayList each time I want the position of a key.

Here is what I tried and what I would want to have:

public static Map<Integer, Object> ObjectsWithId = new LinkedHashMap<>();
public static ArrayList<Integer> ObjectsKeys = new ArrayList<Integer>(ObjectsWithId.keySet());

public int getId(int number) {
         return (number <= ObjectsWithId.size()) ? ObjectsKeys.get(number-1) : -1;
}

Thanks in advance. :)


Solution

  • If your motivation was lightweight of the created object, you may consider creation of an array.

    public int getId(int index) {
         return (index <= ObjectsWithId.size()) ? (int) ObjectsWithId.keySet().toArray()[index-1] : -1;
    }
    

    BTW: Consider renaming the number parameter to index as this is was (I presume) your intention.