Iterating Over a Collection


// For a set or list // collection is the set or list object for (Iterator it=collection.iterator();       it.hasNext(); ) {     Object element = it.next(); } // For keys of a map for (Iterator it =map.keySet().iterator();      it.hasNext(); ) {     Object key = it.next(); } // For values of a map for (Iterator it =map.values().iterator();      it.hasNext(); ) {     Object value = it.next(); } // For both the keys and values of a map for (Iterator it =map.entrySet().iterator();      it.hasNext(); ) {     Map.Entry entry = (Map.Entry)it.next();     Object key = entry.getKey();     Object value = entry.getValue(); }



The java.util package contains an Iterator class that makes iterating over a collection a relatively simple task. To iterate over a collection object, you first obtain an Iterator object by calling the iterator() method on the collection object. Once you have the Iterator object, you can step though it using the next() method. The next() method will return the next item in the collection. Because the next() method returns a generic Object type, you should cast the return value to be the type you are expecting. Using the hasNext() method, you can check to see if there are additional elements that have not yet been processed. This makes it convenient to create a "for" loop as shown in this phrase to step through all the elements in a collection.

In the previous phrase, we show how to iterate over a set or list, the keys of a map, the values of a map, and both keys and values of a map.

Note

You might want to use iterators to expose collections through APIs. The advantage of exposing the data through an iterator is that the calling code does not have to know or care about how the data is stored. With this implementation, you could change the collection type without having to change the API.





JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net