Michał Wolnicki
Michał Wolnicki

Reputation: 285

use stream to sum all values from array stored in map

I have a map which looks like this:

Map<String,String[]> urlFormEncoded = new HashMap<String,String[]>();

and I would like to sum all values stored in String[] arrays as a double value I tried something like this:

double requestAmount = urlFormEncoded.entrySet().stream().mapToDouble(k -> Arrays.stream(k.getValue()).).sum();

but unfortunately I don't know how to convert this String[] to value :( I would like to do this using streams and lambda expressions

Upvotes: 2

Views: 1233

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

The first step would be to convert each String[] as a DoubleStream.

Arrays.stream(arr).mapToDouble(Double::valueOf)

Then you have to flatMap those streams to get a single DoubleStream will all the double values.

.flatMapToDouble(arr -> Arrays.stream(arr).mapToDouble(Double::valueOf))

So you end up with:

double requestAmount = 
    urlFormEncoded.values()
                  .stream()
                  .flatMapToDouble(arr -> Arrays.stream(arr).mapToDouble(Double::valueOf))
                  .sum();

Note that you don't need to use the entrySet() if you plan to work only on the values, you can directly use values().

Upvotes: 10

Related Questions