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.
Eating my own dog's food and implementing what I suggested in a comment (UNTESTED, but it should work -- note that you should use
super
where appropriate, this is not my forte):Usage:
No; you can't do that.
Default methods are not the same as extension methods; they can only be defined within the original interface.
If you want to have a lightweight view to a
List
applying aFunction
and supporting chaining you can do it like this:It supports a GUAVA style creation of a mapped list while still allowing to use the
Stream
API with the mapped list evaluating all values lazily:If you want to create a
List
with pre-calculated values out of it you can simply usenew ArrayList<>(mappedList)
.C# extension methods are great and provide and easy mechanism to extend C# collections with own methods.
But now there are streams in java. Based on @fge response I came with this snippet to write own extension methods on streams:
And to see it in action: