#java #java-stream
#java #java-stream
Вопрос:
У меня есть следующее…
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);
}
Но я бы хотел, чтобы возвращаемый тип был Map<String, Integer>
вместо. Как мне принудить Object
к a String
?
Ответ №1:
Поскольку у вас есть Stream<String>
, это можно вывести, просто объявив карту с типом ключа String
:
Map<String, Integer> map =
stream.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum));
Ответ №2:
В этом нет проблем:
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);
}