java8泛型包括,带有泛型的Java 8 Lambdas的使用

Is it possible to do this using Predicate interface.

I have a client class that utilizes functions provided by a MathUtility class. Whatever the Mathmatical operation it should happen only within the MathUtility class.

//in client

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

//in utility

class MathUtility {

public static T sumWithCondition(List numbers, Predicate condition) {

return numbers.parallelStream()

.filter(condition)

.map(i -> i)

.reduce(0, T::sum); //compile time error

}

public static T avgWithCondition(List numbers, Predicate condition) {

//another function

}

//lot many functions go here

}

Right now it fails with this error - The method reduce(T, BinaryOperator) in the type Stream is not applicable for the arguments (int, T::sum)

Note: I do not want to write sum functions for different Number types

解决方案

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

As Aaron Davis stated in a comment above, you can pass the reduction parameters to the method itself.

public static T sumWithCondition(List numbers, Predicate condition, T identity, BinaryOperator accumulator) {

return numbers.parallelStream().filter(condition).reduce(identity, accumulator);

}

An example would be:

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

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

>> 14

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

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

>> 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值