Method #1
Iterating over Entries
Map<Integer, Integer>; map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
cons: NullPointerException will be thrown if you try to iterate over a null map. You should always check for null references before iterating.
Method #2
Iterating over either Key or Value Sets
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
//iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
pros: If all you need is either key sets or value sets, this method is about 10% faster than iteration over entrySet(), and also cleaner.Method #3
Iterating using Iterator
--With Generics
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
The same method can be used for obtaining the key and value sets respectively. Its performance is equal to for-each loop.
pros: It is the only way if you want to remove entries during iteration by implementing iterator.remove(). If you do this in for-each loop, you will get unpredictable results.
cons: Look a little redundant than other methods.
Iterating over key sets and search values (inefficient)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
I hope these methods to work on in solving the technical issues. However, thanks for sharing this useful blog. I am just convinced with your words for solution.
ReplyDelete