Java 8流:myList.streammapFoo :: bar.collectCollectors.toList的简写

问题描述

以下内容是否有通用的缩写?欢迎使用诸如Guava之类的外部依赖项。

myList.stream().map(Foo::bar).collect(Collectors.toList());

如果我必须实现它,它将类似于:

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

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

static <T,U,V extends Iterable> V<U> mapApply(V<T> iterable,U> function) {
    return iterable.stream().map(function).collect(???);
}

解决方法

如果Foo::bar再次返回Foo的实例,即您需要再次将T转换为T,然后可以使用使用UnaryOperator<T>的{​​{3}},因此每一项都被相同类型的项所代替。此解决方案会更改原始列表。

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

如果要将T转换为R,您所能做的就是使用当前的解决方案并按以下顺序使用stream()-> map()-> { {1}}方法调用或简单的迭代。

包装此方法的静态方法也将执行相同的操作。请注意,您无法使用相同的方式同时从collect()Stream创建Collection。还可以通过您的自定义Iterable

  • Collector是输入TCollection的通用类型。
  • Iterable是映射函数结果的通用类型(从R映射到T

来自R

Collection<T>
List<Bar> listBarFromCollection = mapApply(collectionFoo,Foo::bar,Collectors.toList());

来自static <T,R> List<R> mapApply(Collection<T> collection,Function<T,R> function) { return collection.stream() .map(function) .collect(Collectors.toList()); }

Iterable<T>
List<Bar> listBarFromIterable = mapApply(iterableFoo,Collectors.toList());

...带有static <T,R> List<R> mapApply(Iterable<T> iterable,R> function) { return StreamSupport.stream(iterable.spliterator(),false) .map(function) .collect(Collectors.toList()); }

如果您要传递自定义Collector,则应为Collector,方法的返回类型为Collector<R,?,U> collector而不是U。正如@Holger指出的那样,将List<R>传递给方法与调用实际的Collector-> stream()-> map()并没有太大区别。

,

您可以实现以下方法:

public class StreamShorthandUtil {
    
    public static <T,U,V extends Collection<T>,W> W mapApply(V in,U> function,Collector<U,W> collector) {
        return in.stream().map(function).collect(collector);
    }

    // main class for testing
    public static void main(String[] args) {
        List<String> numbersAsString = Arrays.asList("1","2","3","4","5");
        List<Integer> numbers = mapApply(numbersAsString,Integer::parseInt,Collectors.toList());
    }
}

此方法除了输入和映射器功能外,还具有一个Collector参数,用于定义返回的类型。

,

对于collect(又名map)等方法,您可以直接在具有协变返回类型的集合上使用Eclipse Collections,它具有丰富的API。

例如:

MutableList<Foo> fooList;
MutableList<Bar> barList = fooList.collect(Foo::bar);

MutableSet<Foo> fooSet;
MutableSet<Bar> barSet = fooSet.collect(Foo::bar);

MutableBag<Foo> fooBag;
MutableBag<Bar> barBag = fooBag.collect(Foo::bar);

Iterate实用程序类也可以与任何Iterable一起使用,并提供丰富的协议集。

Iterable<Foo> fooIterable;
List<Bar> barList = Iterate.collect(fooIterable,new ArrayList<>());
Set<Bar> barSet = Iterate.collect(fooIterable,new HashSet<>());

注意:我是Eclipse Collections的提交者。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...