Amar Dwivedi Jr. Amar Dwivedi Jr. - 5 months ago 8
Java Question

Should we traverse map? Why?

If we are using map,I think there is no need for traverse object by for each loop or other way. We have a unique key and value so we can easily find value.
I faced this question so many time in interview. I don't think so this question is
correct. Please help me in regarding question.

Answer

You should traverse a map when ... you need to traverse a map. You're correct that if you have a key, you don't need to do any traversal; just use the key. But there are times you don't have a key. For instance, imagine a map keyed by people's names with their ages as values:

Map<String, Integer> m = new HashMap<String, Integer>();
// Presumably these are added by a user or similar
m.put("Joe", 27);
m.put("Mohammad", 42);
m.put("Maria", 29);

Later we need to output all the names and ages; we'll traverse the map (more technically, we'll traverse its entry set):

for (Map.Entry<String, Integer> e : m.entrySet()) {
    System.out.println(e.getKey() + ": " + e.getValue());
}

Other times we might traverse keySet or values.

Comments