【发布时间】:2019-09-04 14:45:00
【问题描述】:
我正在做一个练习来计算短语中的单词。
我有一个我很乐意将短语拆分为单词标记的正则表达式,因此我可以使用基本循环完成工作 - 没问题。
但我想使用流将字符串收集到地图中,而不是使用基本循环。
我需要每个单词作为一个 key,现在,我只想将整数 1 作为值。
在网上做了一些研究后,我应该能够将单词列表收集到一个地图中,如下所示:
public Map<String, Integer> phrase(String phrase) {
List<String> words = //... tokenized words from phrase
return words.stream().collect(Collectors.toMap(word -> word, 1));
}
我已经尝试过这个和几个变体(投射word,使用Function.identity()),但不断收到错误:
The method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) in the type Collectors is not applicable for the arguments ((<no type> s) -> {}, int)
迄今为止我发现的任何示例都只使用字符串作为值,但否则表明这应该没问题。
我需要进行哪些更改才能完成这项工作?
【问题讨论】:
-
使用
word -> 1而不仅仅是1,因为需要一个函数。
标签: java java-stream java-11 collectors