How to list elements in Collection in java?

We can use Iterator to list the elements in java. We can use Iterator's hasNext() and next() methods to list the elements in Collection. hasNext() method is used to check the whether collection contains any more elements, so we can use this to get the highest boundry of collection list. next() method returns next element of an iteration. Lets see how we can use these methods to iterate over the various collections such as lists, maps etc.

Iterating over List or Set :

If we have collection of type list such as ArrayList or set such as HashSet then we can iterate over the Collection using Iterator till hasNext returns true and get the element using next() method.


for (Iterator iter = collectionDemo.iterator(); iter.hasNext(); ) {
Object elementInCollection = iter.next(); //Getting the item in collection in collection.
}

Iterating over Keys of map :

In case of Maps we have key - value pairs , if we want to iterate over the keys of Map we need to get iterator from keySet of map for this we have method keySet(). Lets see how we can iterate over the keys of map

for (Iterator iter = mapDemo.keySet().iterator(); iter.hasNext(); ) {
Object elementInCollection = iter.next(); //Getting the keys in a map.
}

Iterating over the values of Map :

For iterating over values of map, we can get the values from map using mapDemo.values() and iterate over it.

for ( Iterator iter = mapDemo.keySet().values(); iter.hasNext(); ) {
Object elementInCollection = iter.next(); //Getting the values in a map.

}


Iterating over both keys and values in a Map using entrySet :

For iterating over both keys and values in a Map we can use entry set as follows :


for (Iterator iter= mapDemo.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entryVal = (Map.Entry) iter.next();
Object key = entryVal.getKey();
Object value = entryVal.getValue();

}

This way we can use Iterator to list the elements in the collection in java using methods like hasNext, next etc.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

1 comments: