Peter
Peter

Reputation: 71

Retrieving information from HashMap

I defined a hashmap as follows

HashMap<String, List<String>> hashmap = new HashMap<String, List<String>>();

I can get its content out by doing

Set<Map.Entry<String, List<String>>> keys = hashmap.entrySet();
for (Map.Entry<String,List<String>> entry : hashmap.entrySet()) {
    String key = entry.getKey(); 
    List<String> thing = entry.getValue();
    System.out.println (key);
    System.out.println (thing);
}

However, I would like to know:

Upvotes: 0

Views: 154

Answers (2)

Blake Yarbrough
Blake Yarbrough

Reputation: 2316

Instead of manually getting the set of keys, how about using the keySet() method on the HashMap object from Java?

Use of keySet() looks like:

Set<String> keys = hashmap.keySet();

For the third bullet, see the size() method.

Upvotes: 1

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22214

Assuming that String key = "str"; exists in the map. You can:

int mapSize = hashmap.size(); // get the map's size
List<String> list = hashmap.get("str"); // get a list for a key
String first = hashmap.get("str").get(0); // get a string in a list
int listSize = hashmap.get("str").size(); // get the size of a list
char ch = hashmap.get("str").get(0).charAt(0); // get a char of a string in a list in the map

Upvotes: 2

Related Questions