我有一个与 this 类似的用例堆栈溢出问题并尝试使用它而不将结果存储在 List<List<String>>
中而是调用 stream()
就在上面。
如果我不将其分配给List<List<String>>
,我会遇到一个奇怪的编译时错误因为类型不匹配。要重现该问题,只需注释掉输出的分配即可。
问题是为什么会出现这个编译错误?又该如何解决呢?
public static void main(String args[]) {
List<String> input = Arrays.asList("RED", "RED", "BLUE", "BLUE", "BLUE", "BLUE", "RED", "RED");
List<List<String>> output = // if this line commented it doesn't compile
input.stream()
.collect(Collector.of(
ArrayList::new,
(accumulator, item) -> {
if (accumulator.isEmpty()) {
List<String> list = new ArrayList<>();
list.add(item);
accumulator.add(list);
} else {
List<String> last = accumulator.get(accumulator.size() - 1);
if (last.isEmpty() || last.get(0).equals(item)) {
last.add(item);
} else {
List<String> list = new ArrayList<>();
list.add(item);
accumulator.add(list);
}
}
},
(left, right) -> {
left.addAll(right);
return left;
}
));
}
我的想法是像这样使用它:
input.stream()
.collect(Collector.of(.....))
.stream()
.(and do something else)
最佳答案
Java 中的函数本身没有类型。它们是多重表达式。这意味着它们的类型应该从上下文中推断出来。它适用于 Collector.of()
的所有参数.
List<List<String>> output
- 提供target type ,如果没有它,类型推断机制就无法知道您的 Collector 预计会生成什么类型的对象。
要使代码编译,您可以在调用 Collector.<all the types of functions used in collector here>of()
时使用类型见证 .
编译此流语句的最简单方法是提供累加器的显式参数类型:
(List<List<String>> accumulator, String item) ->
{
...
},
关于Java Stream - 收集器内的类型推断问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73667078/