Iterator
3 CURSORS OF JAVA
- Enumeration (I)
- Iterator (I)
- ListIterator (I) : Provides 2 way iteration with list.previous() adn list.next()
3 main methods of iterator API
hasNext()
next()
remove(object) -> to avoid concurrent modification exception while iterating
List Iterator
Maps
Iterating a Map(TreeMap or HashMap) via KeySet
//Set keyset = map.keySet();
//iterator<E> itr= keyset.iterator();
iterator<E> itr= map.keySet().iterator();
while (itr.hasNext()){
int key = itr.next
int value = map.get(key)
}
Iterating a Map(TreeMap or HashMap) via EntrySet
//Set set = map.entrySet();
//Iterator<Map.Entry<Integer,String>> itr = set.iterator()
Iterator<Map.Entry<Integer,String>> itr = map.entrySet().iterator();
while (itr.hasNext()){
//itr.getKey(), itr.getValue
int key = itr.getKey();
int value = itr.getValue();
}
For Each Loop (Read Only Loop)
For each loop for Map
//For Each Loop
for(Int key :map.keySet()){
int value = map.get(key);
}