【问题标题】:Count frequency of each word from list of Strings using Java8使用Java8计算字符串列表中每个单词的频率
【发布时间】:2020-04-07 10:21:26
【问题描述】:

我有两个字符串列表。需要在另一个字符串列表中创建一个列表的每个字符串出现的映射。如果一个字符串出现的次数超过了单个字符串,则应计为一次。

例如:

String[] listA={"the", "you" , "how"}; 
String[] listB = {"the dog ate the food", "how is the weather" , "how are you"};

Map<String, Integer> map 会将键作为来自listA 的字符串,并将值作为出现。所以 map 的键值是:("the",2)("you",1)("how",2)

注意:虽然"the""the dog ate the food" 中重复了两次,但它在同一个字符串中只计为一次。

如何使用 编写此内容?我尝试了这种方法但不起作用:

Set<String> sentenceSet = Stream.of(listB).collect(Collectors.toSet());

Map<String, Long> frequency1 =  Stream.of(listA)
    .filter(e -> sentenceSet.contains(e))
    .collect(Collectors.groupingBy(t -> t, Collectors.counting()));

【问题讨论】:

    标签: java-stream java arrays java-8 java-stream


    【解决方案1】:

    您需要从listB 中提取所有单词,并仅保留那些也在listA 中列出的单词。然后你只需收集对词 -> 计数到Map&lt;String, Long&gt;

    String[] listA={"the", "you", "how"};
    String[] listB = {"the dog ate the food", "how is the weather" , "how are you"};
    
    Set<String> qualified = new HashSet<>(Arrays.asList(listA));   // make searching easier
    
    Map<String, Long> map = Arrays.stream(listB)   // stream the sentences
        .map(sentence -> sentence.split("\\s+"))   // split by words to Stream<String[]>
        .flatMap(words -> Arrays.stream(words)     // flatmap to Stream<String>
                                .distinct())       // ... as distinct words by sentence
        .filter(qualified::contains)               // keep only the qualified words
        .collect(Collectors.groupingBy(            // collect to the Map
            Function.identity(),                   // ... the key is the words itself
            Collectors.counting()));               // ... the value is its frequency
    

    输出:

    {the=2, how=2, you=1}

    【讨论】:

    • 用 set 代替 list Set&lt;String&gt; qualified = new HashSet&lt;&gt;(Arrays.asList(listA));
    • 谢谢尼古拉斯。添加独特后它可以完美运行
    • 顺便说一句,您或任何人可以分享一个很好的资源来练习 java8 吗?谢谢
    • 我从专门针对 OCAJP 和 OCPJP 认证考试的书中学到了很多关于 Java 8 的知识。但是,最适合我的资源是在 StackOverflow 上进行试验和回答:D
    【解决方案2】:

    建议您为第一个字符串中的项目创建一个哈希表。然后遍历第二个列表中的项目,检查它是否在哈希表中。在第一个列表中添加元素时,测试它是否已经存在并决定是否要保留计数。例如,您可以将单词所在的句子存储为键的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 2014-10-16
      相关资源
      最近更新 更多