gpt4 book ai didi

java - 为什么不能使用 Guava 的恒等函数来代替将列表转换为可迭代的函数?

转载 作者:行者123 更新时间:2023-11-30 03:21:53 24 4
gpt4 key购买 nike

由于遗留原因,我必须使用 Java 7 和 Guava 重新实现一些 Java 8 代码。原始代码如下所示:

someMethodReturningSetofListofStrings().stream()
.forEach((List<String> ts) -> ts.stream()
.forEach(...);

对于 Guava ,我将选择 FluentIterable类,这是我的尝试:

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 .

最佳答案

这是类型推断失败,在这种情况下,您始终可以显式提供类型

transformAndConcat(Function.<List<String>>identity());

在java8中,改进了类型推断,以下代码在java8中编译

transformAndConcat(Function.identity());

关于java - 为什么不能使用 Guava 的恒等函数来代替将列表转换为可迭代的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31146028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com