为什么不能使用 Guava 的身份函数来代替将列表转换为可迭代对象的函数?
Why can't Guava's identity function be used in place of a function that transforms a list to an iterable?
由于遗留原因,我必须使用 Java 7 和 Guava 重新实现一些 Java 8 代码。原始代码如下所示:
someMethodReturningSetofListofStrings().stream()
.forEach((List<String> ts) -> ts.stream()
.forEach(...);
对于 Guava,我将使用 FluentIterable class,这是我的尝试:
Function<List<String>, Iterable<String>> f = new Function<List<String>, Iterable<String>>() {
public Iterable<String> apply(List<String> list) { return list; }
}
FluentIterable.from(someMethodReturningSetofListofStrings()).transformAndConcat(f);
我认为定义函数 f
是不必要的,因为它是恒等函数,我可以只使用 Functions#identity().
但是我的 IDE (Intellij IDEA 14) 抱怨 transformAndConcat(List<String>, Iterable<?>) cannot be applied to Function<Object, Object>
。我不明白为什么,因为 List
显然是 Iterable
.
使用Iterables.concat
:
Iterables.concat(someMethodReturningSetofListofStrings())
这是类型推断失败,在这种情况下,您始终可以明确提供类型
transformAndConcat(Function.<List<String>>identity());
在java8中改进了类型推断,下面的代码在java8
中编译
transformAndConcat(Function.identity());
由于遗留原因,我必须使用 Java 7 和 Guava 重新实现一些 Java 8 代码。原始代码如下所示:
someMethodReturningSetofListofStrings().stream()
.forEach((List<String> ts) -> ts.stream()
.forEach(...);
对于 Guava,我将使用 FluentIterable class,这是我的尝试:
Function<List<String>, Iterable<String>> f = new Function<List<String>, Iterable<String>>() {
public Iterable<String> apply(List<String> list) { return list; }
}
FluentIterable.from(someMethodReturningSetofListofStrings()).transformAndConcat(f);
我认为定义函数 f
是不必要的,因为它是恒等函数,我可以只使用 Functions#identity().
但是我的 IDE (Intellij IDEA 14) 抱怨 transformAndConcat(List<String>, Iterable<?>) cannot be applied to Function<Object, Object>
。我不明白为什么,因为 List
显然是 Iterable
.
使用Iterables.concat
:
Iterables.concat(someMethodReturningSetofListofStrings())
这是类型推断失败,在这种情况下,您始终可以明确提供类型
transformAndConcat(Function.<List<String>>identity());
在java8中改进了类型推断,下面的代码在java8
中编译transformAndConcat(Function.identity());