use stream to sum all values from array stored in map

早过忘川 提交于 2019-12-24 17:43:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!