Java 8 流:myList.stream().map(Foo::bar).collect(Collectors.toList()) 的简写

And*_*ong 5 java generics java-8 java-stream collectors

以下是否有通用的简写?欢迎像番石榴这样的外部依赖项。

myList.stream().map(Foo::bar).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

如果我必须实现它,它会是这样的:

static <T, U> List<U> mapApply(List<T> list, Function<T, U> function) {
    return list.stream().map(function).collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)

有没有适用于任何 Iterable 的?如果没有,我该怎么写?我开始这样思考:

static <T, U, V extends Iterable> V<U> mapApply(V<T> iterable, Function<T, U> function) {
    return iterable.stream().map(function).collect(???);
}
Run Code Online (Sandbox Code Playgroud)

Nik*_*las 6

在这种情况下再次Foo::bar返回一个实例Foo,即。您需要再次转换TT,然后您可以使用List::replaceAllwhich uses UnaryOperator<T>,因此每个项目都被替换为相同类型的一个。此解决方案改变了原始列表。

List<String> list = Arrays.asList("John", "Mark", "Pepe");
list.replaceAll(s -> "hello " + s);
Run Code Online (Sandbox Code Playgroud)

如果您想转换TR,您所能做的就是使用您当前的解决方案以及一系列stream()-> map()->collect()方法调用或简单的迭代。

包装 this 的静态方法也可以这样做。请注意,您不能创建一个Stream来自CollectionIterable使用相同的方式。也可以随意传递您的 custom Collector

  • T是输入Collection或的通用类型Iterable
  • R是映射函数结果的泛型类型(从T到映射R

Collection<T>

List<Bar> listBarFromCollection = mapApply(collectionFoo, Foo::bar, Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
static <T, R> List<R> mapApply(Collection<T> collection, Function<T, R> function) {
    return collection.stream()
        .map(function)
        .collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)

Iterable<T>

List<Bar> listBarFromIterable = mapApply(iterableFoo, Foo::bar, Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
static <T, R> List<R> mapApply(Iterable<T> iterable, Function<T, R> function) {
    return StreamSupport.stream(iterable.spliterator(), false)
        .map(function)
        .collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)

...与Collector

如果你想传递一个自定义的Collector,它会是Collector<R, ?, U> collector和方法的返回类型U而不是List<R>. 正如@Holger 指出的那样,将 a 传递Collector给方法与调用实际stream()-> map()->没有太大区别collect()