BullyWiiPlaza
BullyWiiPlaza

Reputation: 19185

Getting Map Value Pairs Using Index

Is there a way of iterating a LinkedHashMap (which has a defined order) by using an index instead of a foreach loop? I need to access elements using index.

The following code prints the entire map:

public void print(Map<String, Integer> map)
{
    for (Map.Entry<String, Integer> entryMap : map.entrySet())
    {
        System.out.println(entryMap.getValue() + " = " + entryMap.getKey());
    }
}

How can I do the same but access the elements using index instead?

public void print(Map<String, Integer> map)
{
    for (int i = 0; i< map.size(); i++)
    {
        // getValue() and getKey() are undefined
        System.out.println(map.get(i).getValue() + " = " + map.get(i).getKey());
    }
}

The following only returns the keys, but I also need the values:

public String getByIndex(Map<String, Integer> map, int index)
{
    List<String> keys = new ArrayList<>(map.keySet());

    return (String) keys.get(index);
}

Upvotes: 1

Views: 5201

Answers (3)

Radiodef
Radiodef

Reputation: 37845

Well you can write a method to do this.

public static <K, V> Map.Entry<K, V> getEntryByIndex(Map<K, V> map, int i) {
    if(i >= map.size()) {
        throw new IndexOutOfBoundsException(String.valueOf(i));
    }

    // use Iterator
    Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();

    // skip to i
    for(; i > 0; --i) {
        it.next();
    }

    return it.next();
}

This pretty much treats it like a linked list. If you are finding you do this a lot you may want to permanently keep an ArrayList along with the Map.

Upvotes: 2

ToYonos
ToYonos

Reputation: 16833

Try this :

List<String> keys = new ArrayList(map.keySet());
for (int i = 0; i < keys.size(); i++)
{
    String key = keys.get(i);
    Integer value = map.get(key);
    //...
}

Upvotes: 3

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21728

One of the possible workarounds would be to put all keys also into ArrayList where they can be accessed using index. Direct access seems not possible because keySet returns a set that does not support the indexed access.

Upvotes: 0

Related Questions