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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.