Use of Virtual Extension methods in the Java 8 APIs

In wrote a bit about Virtual extension methods here and here. I thought of going over this implementation in the JDK, so that it will give us an idea of how these can be applied.

also read:

As I told earlier, the main intention of adding the virtual extension methods was to provide an option to extend the existing interfaces (by adding new methods) without breaking the existing usages. Consequently the main contender for this is the Collection interface in java.util package. All the collection classes in Java implement this interface. Few methods were added to the Collection interface to provide support for the new collections API.

Lets consider the retainAll method as defined below (copied as is from the source distributed with the JDK):

 * Retains all of the elements of this collection which
 * match the provided predicate.
 * @param filter a predicate which returns {@code true}
 * for elements to beretained.
 * @return {@code true} if any elements were retained.
// XXX potential source incompatibility with retainAll(null)
// now being ambiguous
boolean retainAll(Predicate<? super E> filter) default {
    return CollectionHelpers.retainAll(this, filter);

New CollectionHelpers class is introduced which contains the implementation of various methods used as virtual extension methods. Also notice that the method in the Collection interface doesn’t have any code/implementation details, instead they refer to methods from another class (CollectionHelpers in this case).

The CollectionHelpers.retainApp is defined as (From the source for CollectionHelpers):

public static <E> boolean retainAll(Collection<E> collection,
                                    Predicate<? super E> filter ) {
  boolean retained = false;
  Iterator<E> each = collection.iterator();
  while(each.hasNext()) {
    if(!filter.test( {
    } else {
      retained = true;
  return retained;

There are numerous such examples in the JDK 8, and one can explore different options from the source for the Java APIs.

Leave a Reply

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

Pin It on Pinterest

Share This

Share this post with your friends!