gpt4 book ai didi

java - 将一个 HashMap 缩减为另一个 HashMap

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:05:16 27 4
gpt4 key购买 nike

我从这样的字符串开始:

"train, Train, bike, BIKE, car...etc"

旅行类型,需要返回一个HashMap<String, Integer>() ,例如:

(train, 4), (car, 6), (bike, 2)

数字表示该旅行类型被看到的次数

就我所知,将字符串映射到这样的初始 HashMap 中:

(train, 1), (train, 1), (car, 1), (car, 1)...etc

与:

public static HashMap<String, Integer> countTravelTypes(String travelTypes) {
return Arrays.stream(travelTypes.toLowerCase().replace(" ", "")
.split(","))
.map(s -> new HashMap<String, Integer>(){{put(s, 1);}})
//The line below isn't right but it's as close as I could get
.reduce(0, map -> map.key, Integer.sum(v))
}

你现在能帮我减少它吗,所以基本上总结了所有的火车,表明有 4

最佳答案

我们可以使用Collectors.summingInt()对于 Map<String, Integer> 类型的输出 map :

Map<String, Integer> result =  
Stream.of("train, Train, bike, BIKE, car, BIKE, Train".split(", "))
.collect(Collectors.groupingBy(i -> i, Collectors.summingInt(i -> 1)));

关于java - 将一个 HashMap 缩减为另一个 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55199408/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com