问题
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
回答1:
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().
来源:https://stackoverflow.com/questions/31559046/use-stream-to-sum-all-values-from-array-stored-in-map