Use of Java 8 Lambdas with Generics

后端 未结 4 1795
执念已碎
执念已碎 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:15

    A much simpler approach I tired is this.

    The point to be noted is that the addition logic doesn't happen at the invoking side instead only within the MathUtility. The downside here is that you have to create Addition classes for every Number type you want the + operation.

    System.out.println(
                    MathUtility.sum(listOfInts, i->i<4, new MathUtility.IntegerAddition()).get()
    ); 
    
    class MathUtility {
    
        static class IntegerAddition implements BinaryOperator {
    
            @Override
            public Integer apply(Integer t, Integer u) {
                return t + u;
            }
    
        }
    
    
        public static  Optional sum(List list, Predicate condition, BinaryOperator operation){
            //ability to add is only here
                return list.parallelStream()
                .filter(condition)
                .map(i -> i)
                .reduce(operation);
        }
    
    }
    

提交回复
热议问题