[英]How do I use Java stream collect to create a map with a String as the key instead of object?
I have the following...我有以下...
public Map<Object, Integer> getRankings(){
Stream<String> stream = votes.stream();
Map<Object, Integer> map = stream
.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
return Vote.sortByValues(map);
}
But I would like the return type to be Map<String, Integer>
instead.但我希望返回类型改为
Map<String, Integer>
。 How do I coerce the Object
to a String
?如何将
Object
强制为String
?
Since you have a Stream<String>
, it can be inferred by just declaring the map with a key type of String
:由于您有一个
Stream<String>
,因此可以通过使用String
键类型声明 map 来推断它:
Map<String, Integer> map =
stream.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
There's no problem in this:这没有问题:
public Map<String, Integer> getRankings(){
Stream<String> stream = votes.stream();
Map<String, Integer> map = stream
.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
return Vote.sortByValues(map);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.