【发布时间】:2022-11-03 00:41:29
【问题描述】:
我正在尝试使用流过滤地图。我过滤的谓词/条件是另一个流。我目前遇到了 IllegalStateException 的问题,可能是因为我正在访问一个已经被访问过的流。
Map<Integer, Double> table = Map.of(10, 8.0,
15, 10.0,
20, 28.0,
40, 40.0);
Stream<Double> streamDbl = getDoublefromInt(table, Stream.of(20, 40));
参考this 网站,我想出了类似下面的代码段,但它不起作用。
public static Stream<Double> getDoublefromInt(Map<Integer, Double> table, Stream<Integer> id) {
return table.entrySet().stream
.filter(map -> id.anyMatch(id -> id.equals(map.getKey())))
.map(map -> map.getValue());
}
【问题讨论】:
-
为什么要使用流过滤 Map?首先将流收集到集合/列表中怎么样?
-
每次调用
#anyMatch时,您都会使用第二个流。您很可能需要Set进行快速/散列O(1)#contains检查,而不是需要Stream遍历的Stream -
Stream 不是 IMO 过滤器中工作的工具。使用
Set。它包含方法...contains,它自己完成您在filter操作中的 lambda 中的 lambda 中所做的事情。 -
如果我正确理解了任务,那么您的解决方案就是
return id.map(table::get);在您的getDoublefromInt()
标签: java java-stream