Java Reference
In-Depth Information
Iterator , but leaves the remove() method unimplemented (per the Iterator
Java documentation, UnsupportedOperationException should be thrown). Al-
ternatively, your iterator() method could return the Iterator from an unmodifi-
able Collection obtained through a call to the Collec-
tions.unmodifiableCollection() class method. You are encouraged to ex-
plore these two options. To give you a start, one possible implementation of Unmodi-
fiableIterator has been provided in the source code download (see Unmodifi-
ableIterator.java ).
As you have seen in this recipe, the Iterable interface allows you to create iter-
able objects that are compatible with a for-each implementation. This is very useful
when you want to design a custom collection-based class that encapsulates implement-
ation details. Just keep in mind that in order to enforce the encapsulation and prevent
modification of your underlying collection, you should implement one of the solutions
mentioned in the preceding note.
7-8. Iterating Over Collections
Problem
Your application contains Collection types, and you want to iterate over the ele-
ments within them.
Solution
Generate a stream on any type that extends or implements
java.util.Collection , and then perform the desired task(s) on each element of
the collection. In the following code, an ArrayList loaded with Stock objects is
used to demonstrate the concept of streams.
public class StreamExample {
static List<Stock> myStocks = new ArrayList();
private static void createStocks(){
myStocks.add(new Stock("ORCL", "Oracle", 500.0));
Search WWH ::




Custom Search