Use of Java 8 Lambdas with Generics

后端 未结 4 1796
执念已碎
执念已碎 2021-02-10 14:37

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

4条回答
  •  不知归路
    2021-02-10 15:16

    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
    

提交回复
热议问题