parsing on HashMap in Java

23,000

Solution 1

Here's how you can get the key set:

Set<A> keys = myMap.keySet();

I don't know what "passing on" means. I don't know what "parsing" means for a HashMap, either. Except for getting the keys out of the Map, this question makes no sense whatsoever. Voting to close.

Solution 2

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();
}

Solution 3

map.keySet() will return you the set containing all keys .. from here you can parse the set and get all the keys

Solution 4

myMap.keySet() ? Not sure what you mean actually.

Solution 5

After passing the map to wherever you're passing it to, the method/class ending up with the map would make the following call to get the set of keys in the map.

Set<A> keys = myMap.keySet();
Share:
23,000
uriel
Author by

uriel

Updated on April 27, 2020

Comments

  • uriel
    uriel about 4 years

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

  • uriel
    uriel over 12 years
    Like that? Set<A> keys = myMap.keySet(); for(A key : keys) myFunction(key) ;