gpt4 book ai didi

java - 将 Java 8 Lambda 与泛型一起使用

转载 作者:搜寻专家 更新时间:2023-11-01 02:02:05 25 4
gpt4 key购买 nike

是否可以使用 Predicate 接口(interface)来做到这一点。

我有一个客户端类,它使用 MathUtility 类提供的函数。无论数学运算是什么,它都应该只发生在 MathUtility 类中。

    //in client 
MathUtility.sum(listOfInts, (Integer i)->{return (i<3);});

//in utility
class MathUtility<T extends Number> {
public static <T extends Number> T sumWithCondition(List<T> numbers, Predicate<T> condition) {
return numbers.parallelStream()
.filter(condition)
.map(i -> i)
.reduce(0, T::sum); //compile time error
}
public static <T extends Number> T avgWithCondition(List<T> numbers, Predicate<T> condition) {
//another function
}
//lot many functions go here
}

现在它失败并出现此错误 - The method reduce(T, BinaryOperator<T>) in the type Stream<T> is not applicable for the arguments (int, T::sum)

注意:我不想为不同的数字类型编写求和函数

编辑:本 Github Notebook 中对此主题的详细讨论

最佳答案

Is there a way to do it without writing a sum function for every possible type of T that i'm expecting?

正如 Aaron Davis 在上面的评论中所述,您可以将缩减参数传递给方法本身。

public static <T> T sumWithCondition(List<T> numbers, Predicate<T> condition, T identity, BinaryOperator<T> accumulator) {
return numbers.parallelStream().filter(condition).reduce(identity, accumulator);
}

一个例子是:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

System.out.println(sumWithCondition(list, i -> i > 1, 0, (a, b) -> a + b));

>> 14

List<BigInteger> list2 = Arrays.asList(BigInteger.ONE, BigInteger.ONE);

System.out.println(sumWithCondition(list2, i -> true, BigInteger.ZERO, (a, b) -> a.add(b)));

>> 2

关于java - 将 Java 8 Lambda 与泛型一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43429030/

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