Search code examples
javalambdaguavajava-8default-method

Extending List<T> in Java 8


I often want to map one list into another list. For example if I had a list of people, and I wanted a list of their names, I would like to do:

GOAL

List<Person> people = ... ;

List<String> names = people.map(x -> x.getName());

Something like this is possible with Java 8:

JAVA 8 VERSION

List<String> names = people.stream()
                           .map(x -> x.getName())
                           .collect(Collectors.toList());

But this is clearly not as nice. In fact, I think using Guava is cleaner:

GUAVA VERSION

List<String> names = Lists.transform(people, x -> x.getName());

However, I do like chaining. So, is my goal possible?

I have heard people say that Java 8 default methods are similar to C# extension methods. With a C# extension method, I could easily add a helper method to IEnumerable<T>:

public static IEnumerable<TRet> Map<T, TRet>(this IEnumerable<T> list, Func<T, TRet> selector)
{
    return list.Select(selector);
}

However I can't figure out how to use default methods to extend an existing interface.

Also, this is obviously a trivial example. In general, I would like to be able to extend the List<T> and Iterable<T> interfaces to make interacting with the streams api easier.


Solution

  • No; you can't do that.

    Default methods are not the same as extension methods; they can only be defined within the original interface.