Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a keyIterator for a LinkedHashMap?

By looking at the source code for LinkedHashMaps from Sun, I see that there is a private class called KeyIterator, I would like to use this. How can I gain access?

like image 704
Bobby Avatar asked Jun 10 '09 21:06

Bobby


People also ask

How get values from LinkedHashMap?

You can convert all the keys of LinkedHashMap to a set using Keyset method and then convert the set to an array by using toArray method now using array index access the key and get the value from LinkedHashMap.

How do I loop through a LinkedHashMap?

There are basically two ways to iterate over LinkedHashMap:Using keySet() and get() Method. Using entrySet() and Iterator.

Can LinkedHashMap have null key?

LinkedHashMap allows one null key and multiple null values. LinkedHashMap maintains order in which key-value pairs are inserted.

Can LinkedHashMap have duplicate keys?

A LinkedHashMap cannot contain duplicate keys. LinkedHashMap can have null values and the null key. Unlike HashMap, the iteration order of the elements in a LinkedHashMap is predictable.


2 Answers

You get it by calling

myMap.keySet().iterator();

You shouldn't even need to know it exists; it's just an artifact of the implementation. For all you know, they could be using flying monkeys to iterate the keys; as long as they're iterated according to the spec, it doesn't matter how they do it.

By the way, did you know that HashMap has a private class called KeyIterator (as do ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, IdentityHashMap, TreeMap, and WeakHashMap)?
Does that make a difference in how you iterate through the keys of a HashMap?


Edit: In reponse to your comment, be aware that if you are trying to iterate over all key-value pairs in a Map, there is a better way than iterating over the keys and calling get for each. The entrySet() method gets a Set of all key-value pairs which you can then iterate over. So instead of writing:

for (Key key : myMap.keySet()) {
    Value val = myMap.get(key);
    ...
}

you should write:

for (Map.Entry<Key, Value> entry : myMap.entrySet()) {
    doSomethingWithKey(entry.getKey());
    doSomethingWithValue(entry.getValue());
    ...
}

You could also iterate over the values with values() if you want.

Note that since keySet, entrySet, and values are defined in the Map interface, they will work for any Map, not just LinkedHashMap.

like image 116
Michael Myers Avatar answered Sep 30 '22 10:09

Michael Myers


It's a private class, so you can't directly use it.

  private class KeyIterator extends LinkedHashIterator<K> {

An instance of it is returned when you use the normal Iterator.

myMap.keySet().iterator()
like image 26
Mike Pone Avatar answered Sep 30 '22 10:09

Mike Pone