markg markg - 8 days ago 5
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
Map<String,Double>
not a
Map<String,Integer>
like above,
However, simply changing the
Integer::sum
to
Double::sum
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()){
thesum+=d;
}


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.

Thanks

Gov Gov
Answer

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
}