Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing on HashMap in Java

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){...}".

like image 257
uriel Avatar asked Dec 03 '22 05:12

uriel


1 Answers

This is a more generic answer based on question title.

Parsing keys & values using 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();
}

Parsing keys using 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.

Parsing values using 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();
}
like image 112
oHo Avatar answered Dec 09 '22 14:12

oHo