The Collection Interface

The Collection Interface

//for example, you have a Collection<String> c, which may be a List,
// a Set, or another kind of Collection. This idiom creates a new ArrayList
// (an implementation of the Listinterface), initially containing all the elements in c.

List<String> list = new ArrayList<String>(c);
  • A Collection represents a group of objects known as its elements.
  • The Collection interface is used to pass around collections of objects where maximum generality is desired.
  • The Collection interface contains methods that perform basic operations, such as int size(), boolean isEmpty(), boolean contains(Object element), boolean add(E element), boolean remove(Object element), and Iterator<E> iterator(). It also contains methods that operate on entire collections, such as boolean containsAll(Collection<?> c), boolean addAll(Collection<? extends E> c), boolean removeAll(Collection<?> c), boolean retainAll(Collection<?> c), and void clear().

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:
.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)
//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(

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 — Structure map

Clickable & Draggable!

The Collection Interface — Related pages: