有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将字符串列表收集到映射中,其中每个字符串都是一个键?

我正在做一个练习,数一数短语中的单词

我有一个我很喜欢的正则表达式,可以将短语分割成单词标记,这样我就可以用基本循环完成这项工作——没问题

但是我希望使用流将字符串收集到映射中,而不是使用基本循环

我需要每个单词作为,现在,我只希望整数1作为值。 在网上做了一些研究后,我应该能够将单词列表收集到一张地图中,如下所示:

public Map<String, Integer> phrase(String phrase) {
    List<String> words = //... tokenized words from phrase
    return words.stream().collect(Collectors.toMap(word -> word, 1));
}

我已经尝试过这一点,以及一些变体(使用Function.identity()铸造word),但不断出现错误:

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)

到目前为止,我发现的任何示例都只使用字符串作为值,但在其他方面表明这应该是可以的

我需要做什么改变才能让这一切顺利进行


共 (1) 个答案

  1. # 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));