我开始使用这样的字符串:
"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)));
你可以使用groupingBy
收集器与counting
下游收集器一起完成这件事。这是它的外观。
Map<String, Long> result = Arrays.stream(source.split(","))
.map(String::trim)
.map(String::toLowerCase)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));