Using the removeIf() Method to Filter a Collection – Collections: Part II


Using the removeIf() Method to Filter a Collection

The following default method of the Collection<E> interface makes the task of filtering a collection much easier, as no explicit iteration is necessary:

Click here to view code image

default boolean removeIf(Predicate<? super E> filter)

All elements that satisfy the predicate defined by the specified filter are removed from this collection. The method returns true or false depending on whether the collection was modified or not. Predicates are covered in §13.6, p. 703.

In Example 15.1, the call to the removeIf() method at (13) takes a Predicate to test whether a name starts with the letter A, resulting in those names satisfying the predicate to be removed from the collection.

Click here to view code image

// [Alice, Dick, Harriet]
collectionOfNames.removeIf(name -> name.startsWith(“A”));        // (13)
// [Dick, Harriet]

Ample examples of filtering can also be found in §13.3, p. 691, and §16.5, p. 910.

Streams

The two methods of the Collections interface shown below allow a collection to be used as the source of a stream. A stream makes the elements of a collection available as a sequence of elements on which sequential and parallel aggregate operations can be performed.

Click here to view code image

default Stream<E> stream()
default Stream<E> parallelStream()

Return a sequential stream or a possibly parallel stream with this collection as its source, respectively.

Example 15.1 illustrates at (14) how a stream can be used to iterate over the collection of names in order to print them in uppercase.

Click here to view code image

collectionOfNames.stream()                                       // (14)
                 .forEach(name -> System.out.print(name.toUpperCase() + ” “));

Details are revealed in §16.4, p. 897, which is devoted entirely to streams, providing many examples of using streams on collections.

Leave a Reply

Your email address will not be published. Required fields are marked *