我使用了来自java8的流API,当我将一个对象映射到另一个对象并将这个对象传递给一个期望供应商的方法时,我得到了一个编译错误。如何将此对象传递给该方法?
为了得到更好的解释,我编写了以下代码:
public class SimpleTest {
public static class B{
public static B mapFrom(A a){
return new B(); //transform to b
}
}
public static class A{
}
public static Integer mapToSomethingElseWith(Supplier<B> b){
return 1;
}
public static void example(){
List<A> a = Lists.newArrayList(new A(),new A(),new A());
List<Integer> l = a.stream()
.map(B::mapFrom)
.map(SimpleTest::mapSomethingElseWith); //does not work. Bad return type in method reference: cannot convert java.lang.Integer to R
.collect(Collectors.toList());
}
}
我目前(丑陋)的解决方案如下所示:
List<Integer> l = a.stream()
.map(B::mapFrom)
.map((b)-> ((Supplier) () -> b) // map to supplier
.map(SimpleTest::mapSomethingElseWith)
.collect(Collectors.toList());
存在着类似但更有表现力的东西?
发布于 2017-07-17 11:31:34
当你写:
List<Integer> l = a.stream()
.map(B::mapFrom)
当Stream<B>
方法返回B
时,您将得到一个B
:
public static B mapFrom(A a){...}
然后,用以下内容链接Stream<B>
:
.map(SimpleTest::mapSomethingElseWith);
mapToSomethingElseWith()
被定义为mapToSomethingElseWith(Supplier<B> b)
。
因此,编译器希望有一个带有as参数的mapToSomethingElseWith()
方法,而不是B
,但是您需要将B
变量传递给它。
解决问题的一种方法是使用带有显式lambda的map()
方法,使用Supplier<B>
调用mapToSomethingElseWith()
。
()-> b
,其中b
是lambda的B
类型的参数,是Supplier<B>
。它实际上不需要arg,它返回一个B
实例。
你可以这样写:
map(SimpleTest::mapSomethingElseWith);
List<Integer> l = a.stream()
.map(B::mapFrom)
.map(b->SimpleTest.mapToSomethingElseWith(()-> b) )
.collect(Collectors.toList());
发布于 2017-07-17 10:52:47
将最后两个map
组合起来怎么样:
List<Integer> l = a.stream()
.map(B::mapFrom)
.map(b -> SimpleTest.mapSomethingElse (() -> b))
.collect(Collectors.toList());
https://stackoverflow.com/questions/45142151
复制相似问题