The Collection Interface: Traversing Collections

//In JDK 8 and later, the preferred method of iterating over a collection is 
//to obtain a stream and perform aggregate operations on it. 
//Aggregate operations are often used in conjunction with lambda expressions 
//to make programming more expressive, using less lines of code:

		
myShapesCollection.stream()
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));
// The for-each construct allows you to concisely traverse a collection or array 
//using a for loop:
		
for (Object o : collection)
    System.out.println(o);
//The following method shows you how to use an Iterator to filter 
//an arbitrary Collection:
		
static void filter(Collection<?> c) {
    for (Iterator<?> it = c.iterator(); it.hasNext(); )
        if (!cond(it.next()))
            it.remove();
}

There are three ways to traverse collections: (1) using aggregate operations (2) with the for-each construct and (3) by using Iterators.

The Collection Interface: Traversing Collections — Structure map

Clickable & Draggable!

The Collection Interface: Traversing Collections — Related pages: