Iterate and stream

Every collection that implements the Collection interface (which extends the Iterable interface) can be iterated over using the enhanced for statement discussed in Chapter 10, Control Flow Statements. Here is an example:

List list = new ArrayList();list.add(null);list.add(1);list.add("ss");list.add(new A());list.add(new B());for(Object o: list){  //code that does something with each element   } 

The Iterable interface also adds the following three methods to the List interface:

  • forEach(Consumer function): It applies the provided function to each collection element
  • iterator(): It returns an object of class Iterator that allows walking through (iterating) each element of the collection and manipulating each of them as needed ...

Get Introduction to Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.