【发布时间】:2020-02-07 10:01:59
【问题描述】:
我有这段代码,它是通过 for 循环实现的。我想用 .stream 和 .map() 函数来编写它。我尝试使用 .map() 函数。但不幸的是,我收到以下错误:
不兼容的类型。必需列表> 但“收集”是 推断为 R:不存在类型变量的实例,因此 Boolean 符合 List 推理变量 T 不兼容 bounds: 等式约束: List lower bounds: Boolean
这是旧代码:
public Iterable<Record> findAll(final List<Long> id) {
final List<Record> result = new LinkedList<Record>();
final List<List<Long>> partitions = ListUtils.partition(id, 10);
for (List<Long> partition : partitions) {
Iterables.addAll(
result,
this.repository.findAll(partition)
);
}
return result;
}
这是我使用 .map() 时的代码
public Iterable<Record> findAll(final List<Long> id) {
final List<Record> result = new LinkedList<Record>();
final List<List<Long>> partitions = ListUtils.partition(id, 10);
List<List<Long>> allPartitions = partitions.stream().map(partition ->{
return Iterables.addAll(result, this.repository.findAll(partition));
}).collect(Collectors.toList());
return result;
}
关于如何解决此问题的任何建议?或者我应该注意什么?
【问题讨论】:
-
试试这个
List<List<Long>> allPartitions = partitions.stream().map(partition ->{ Iterables.addAll(result, this.repository.findAll(partition)); return result; }).collect(Collectors.toList()); -
@HadiJ 我看不出我写的代码有什么不同,而且没有工作
-
Iterables.addAll(result, this.repository.findAll(partition));返回布尔值,而您需要返回List<Long>因为它不兼容。所以我想你应该返回result虽然我不熟悉番石榴。 -
或者这样
return partitions.stream() .flatMap(partition->this.repository.findAll(partition).stream()) .collect(Collectors.toList()); -
this.repository.findAll(partition)返回什么?
标签: java spring-boot java-8 java-stream