应用某些函数后如何有效地计算集合的最大值
2022-09-03 06:57:43
假设你有一个像这样的方法,它计算一些的a的最大值:Collection
ToIntFunction
static <T> void foo1(Collection<? extends T> collection, ToIntFunction<? super T> function) {
if (collection.isEmpty())
throw new NoSuchElementException();
int max = Integer.MIN_VALUE;
T maxT = null;
for (T t : collection) {
int result = function.applyAsInt(t);
if (result >= max) {
max = result;
maxT = t;
}
}
// do something with maxT
}
使用Java 8,这可以转化为
static <T> void foo2(Collection<? extends T> collection, ToIntFunction<? super T> function) {
T maxT = collection.stream()
.max(Comparator.comparingInt(function))
.get();
// do something with maxT
}
新版本的缺点是,对于 相同的值 重复调用 。(具体来说,如果集合的大小为 ,则调用时间,而调用时间)。function.applyAsInt
T
n
foo1
applyAsInt
n
foo2
2n - 2
第一种方法的缺点是代码不太清晰,您无法对其进行修改以使用并行性。
假设您希望使用并行流执行此操作,并且每个元素仅调用一次。这可以用简单的方式写吗?applyAsInt