-1

I want to get a LinkedHashMap key based on index. I have tried this and used a LinkedHashMap implementation instead of HashMap implementation to preserve order of insertion.

I have used below code (from some SO post I can't seem to find) to get Key By Value :

private Long getKeyByValue(Map<Long, String> map, String value) {

    for (Map.Entry<Long, String> entry : map.entrySet()) {
        if (entry.getValue().equalsIgnoreCase(value)) {
            return entry.getKey();
        }
    }

    // -1 if key not found
    return (long) -1;
}

The problem is, above method is useful only when Map value is not custom or not a collection. In my case, I have a Map<String, List<Issues>> where Issues is my own defined class and I want to get, say, 2nd key which is String based on index which is 2, in this case. Suggestions?

Community
  • 1
  • 1
Shubham A.
  • 2,446
  • 4
  • 36
  • 68

1 Answers1

2

how about this:

static <K> K getKeyByIndex( Map<K,?> sortedMap, int index )
{
    assert index >= 0;
    assert index < sortedMap.size();
    for( K key : sortedMap.keySet() )
    {
        if( index == 0 )
            return key;
        index--;
    }
    assert false; //should never happen.
}
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142