I've simple question.
I set:
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(...)
...
Now I want to Loop through myMap and get all the keys (of type A). how can I do that?
I want to get all keys from myMap by loop, and send them to "void myFunction(A param){...}".
This is a more generic answer based on question title.
entrySet()
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(key, value);
...
for (Entry<A, B> e : myMap.entrySet()) {
A key = e.getKey();
B value = e.getValue();
}
//// or using an iterator:
// retrieve a set of the entries
Set<Entry<A, B>> entries = myMap.entrySet();
// parse the set
Iterator<Entry<A, B>> it = entries.iterator();
while(it.hasNext()) {
Entry<A, B> e = it.next();
A key = e.getKey();
B value = e.getValue();
}
keySet()
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(key, value);
...
for (A key : myMap.keySet()) {
B value = myMap.get(key); //get() is less efficient
} //than above e.getValue()
// for parsing using a Set.iterator see example above
See more details about entrySet()
vs keySet()
on question Performance considerations for keySet() and entrySet() of Map.
values()
HashMap<A, B> myMap = new HashMap<A, B>();
...
myMap.put(key, value);
...
for (B value : myMap.values()) {
...
}
//// or using an iterator:
// retrieve a collection of the values (type B)
Collection<B> c = myMap.values();
// parse the collection
Iterator<B> it = c.iterator();
while(it.hasNext())
B value = it.next();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With