【问题标题】:How can I collect a list of strings to a map, where each string is a key? [duplicate]如何将字符串列表收集到地图中,其中每个字符串都是一个键? [复制]
【发布时间】: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 -&gt; 1 而不仅仅是1,因为需要一个函数。

标签: java java-stream java-11 collectors


【解决方案1】:

要克服编译错误,您需要:

return words.stream().collect(Collectors.toMap(word -> word, word -> 1));

但是,这会导致Map 的所有值都为1,如果words 中有重复元素,则会出现异常。

您需要将Collectors.groupingByCollectors.toMap 与合并函数一起使用来处理重复值。

例如

return words.stream().collect(Collectors.groupingBy(word -> word, Collectors.counting()));

return words.stream().collect(Collectors.toMap(word -> word, word -> 1, Integer::sum));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2021-07-21
    • 2012-01-11
    • 2019-07-05
    • 1970-01-01
    • 2020-03-13
    相关资源
    最近更新 更多