扩展列表< T>在Java 8中 [英] 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());
使用Java 8可以实现这样的目标:
Something like this is possible with Java 8:
JAVA 8版本
List<String> names = people.stream()
.map(x -> x.getName())
.collect(Collectors.toList());
但这显然不是很好。事实上,我认为使用Guava更清洁:
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?
我听说有人说Java 8默认方法类似于C#扩展方法。使用C#扩展方法,我可以轻松地将辅助方法添加到 IEnumerable< T>
:
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.
此外,这显然是一个微不足道的例子。一般来说,我希望能够扩展列表< T>
和 Iterable< T>
接口与流api交互更容易。
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.
推荐答案
否;你不能这样做。
默认方法与扩展方法不同;它们只能在原始界面中定义。
Default methods are not the same as extension methods; they can only be defined within the original interface.
这篇关于扩展列表< T>在Java 8中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!