如何解决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
是输入T
或Collection
的通用类型。 -
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的提交者。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。