java list求和_Java 使用stream()将Map<String, List<String>>数据求和(sum)方法代码

2023-05-16

示例Map>的inputMap:{"product":["132377","2123232","312335678","423432","5215566"],"order":["3174252","1468453","1264543","35723112","235775645"]}

1、使用forEach实现Map resultSet = new HashMap<>();

inputMap.forEach((k, v) -> resultSet.put(k, v.stream()

.mapToDouble(s -> computeScore(s)).sum()));

2、使用collect()实现Map finalResult = inputMap.entrySet()

.stream()

.collect(Collectors.toMap(

Entry::getKey,

e -> e.getValue()

.stream()

.mapToDouble(str -> computeScore(str))

.sum()));

或Map finalResult = inputMap.entrySet()

.stream()

.map(entry -> new AbstractMap.SimpleEntry( // maps each key to a new

// Entry

entry.getKey(), // the same key

entry.getValue().stream()

.mapToDouble(string -> computeScore(string)).sum())) // List mapped to

// List and summed

.collect(Collectors.toMap(Entry::getKey, Entry::getValue)); // collected by the same

// key and a newly

// calulcated value

3、Collect的使用

以stream的元素转变成一种不同的结果,可以是一个List,Set或Map。

例如:List filtered = persons .stream() .filter(p -> p.name.startsWith("P")) .collect(Collectors.toList()); System.out.println(filtered);

输出:[Peter, Pamela]

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java list求和_Java 使用stream()将Map<String, List<String>>数据求和(sum)方法代码 的相关文章

随机推荐