markg markg - 1 year ago 193
Java Question

How to do Java lambda sum on Double not Integer?

I have this obscene block of java lambda code that works (it sums a collection of integers, Netbeans IDE wrote it for me....)

Integer thesum = times.values().stream().filter((val) -> (val != null)).reduce(thesum, Integer::sum);

Now the "times" Map changed to a
not a
like above,
However, simply changing the
doesn't work

Double thesum = times.values().stream().filter((val) -> (val != null)).reduce(thesum, Double::sum);//does not work

Why is it different with doubles vs integers?

TBH I actually don't care, because this works and IMO is more understandable anyway

for(double d : times.values()){

But I thought those who enjoy the construction of lambda syntax as a form of human happiness and personal gratification might want to see an answer to this, because it annoyed me almost as much as the general syntax construct itself.


Gov Gov
Answer Source

Aside from the variable 'thesum' not being initialised before use; The code looks fine and compiles & runs as expected in eclipse.

I've added an example below, formatted for clarity

public static void main(String[] args) {
    Map<String,Double> times = new HashMap<>();
    times.put("1", 1.0);
    times.put("2", 2.0);
    times.put("null", null);
    times.put("3", 3.0);
    times.put("4", 4.0);

    Double thesum = 0.0;
    thesum = times.values().stream()
        .filter((val) -> (val != null))
        .reduce(thesum, Double::sum);

    System.out.println(thesum); // 10.0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download