Java Generics and adding numbers together

前端 未结 7 1830
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 07:58

I would like to generically add numbers in java. I\'m running into difficulty because the Numbers class doesn\'t really support what I want to do. What I\'ve tried so far

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 08:29

    since the introduction of Java 8 streams and lambda you can have a shorter solution

    public interface Adder {
    
        static  E sumValues(Collection objectsToSum, BinaryOperator sumOp) {
            return objectsToSum.stream().reduce(sumOp).orElse(null);
        }
    }
    

    and use it as follows

    int sum = Adder.sumValues(List.of(4, 5, 6, 7), Integer::sum);
    

    Note, that Stream::reduce with just accumulator returns Optional that's why I used orElse(null), but I would recommend to send also zero value as parameter to Adder::sumValue

提交回复
热议问题