0

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. :)

2 Answers2

0

How about using for loop ?

If you don't want to create ArrayList you can try below one.

public int getId( int number ) {
    int position = 0;
    int i = 0;

    for ( Map.Entry<Integer, Object> entry : ObjectsWithId.entrySet() ) {
        if ( number == entry.getKey() ) {
            position = i;

            break;
        } else {
            i++;
        }
    }
    return position;
}
Ravi MCA
  • 2,491
  • 4
  • 20
  • 30
0

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.

Chris Jaga
  • 389
  • 4
  • 17