如何将字符串列表收集到映射中,其中每个字符串都是一个键?
How can I collect a list of strings to a map, where each string is a key?
我正在做一个计算短语中单词的练习。
我有一个正则表达式,我很乐意将短语拆分为单词标记,因此我可以使用基本循环完成工作 - 没问题。
但我想使用流将字符串收集到映射中,而不是使用基本循环。
我需要每个单词作为 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)
迄今为止我发现的任何示例都只使用字符串作为值,但在其他方面表明这应该没问题。
我需要更改什么才能使这项工作正常进行?
要克服编译错误,您需要:
return words.stream().collect(Collectors.toMap(word -> word, word -> 1));
但是,这会导致 Map
的所有值都为 1,如果 words
中有重复元素,则会出现异常。
您需要使用 Collectors.groupingBy
或 Collectors.toMap
以及合并函数来处理重复值。
例如
return words.stream().collect(Collectors.groupingBy(word -> word, Collectors.counting()));
或
return words.stream().collect(Collectors.toMap(word -> word, word -> 1, Integer::sum));
我正在做一个计算短语中单词的练习。
我有一个正则表达式,我很乐意将短语拆分为单词标记,因此我可以使用基本循环完成工作 - 没问题。
但我想使用流将字符串收集到映射中,而不是使用基本循环。
我需要每个单词作为 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)
迄今为止我发现的任何示例都只使用字符串作为值,但在其他方面表明这应该没问题。
我需要更改什么才能使这项工作正常进行?
要克服编译错误,您需要:
return words.stream().collect(Collectors.toMap(word -> word, word -> 1));
但是,这会导致 Map
的所有值都为 1,如果 words
中有重复元素,则会出现异常。
您需要使用 Collectors.groupingBy
或 Collectors.toMap
以及合并函数来处理重复值。
例如
return words.stream().collect(Collectors.groupingBy(word -> word, Collectors.counting()));
或
return words.stream().collect(Collectors.toMap(word -> word, word -> 1, Integer::sum));