如何使用JavaStream查找共享键的所有值的平均值?

我在尝试平均 java 中地图的值时遇到了很多麻烦。我的方法接受一个文本文件,并查看以某个字母开头的每个单词的平均长度(不区分大小写并遍历文本文件中的所有单词。

例如,假设我有一个包含以下内容的文本文件:

"Apple arrow are very common Because bees behave Cant you come home"

我的方法目前返回:

{A=5, a=8, B=7, b=10, c=10, C=5, v=4, h=4, y=3}

因为它是看字母,求单词的平均长度,但是还是区分大小写的。

它应该返回:

{A=5, a=8, B=7, b=10, c=10, C=5, v=4, h=4, y=3}

{a=4.3, b=5.5, c=5.0, v=4.0, h=4.0, y=3}

这是我到目前为止。

public static Map<String, Integer> findAverageLength(String filename) {
    
     Map<String, Integer> wordcount = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
       
        try 
        {
            Scanner in = new Scanner(new File(filename));
            List<String> wordList = new ArrayList<>();
            while (in.hasNext()) 
            {
                wordList.add(in.next());
            }

            wordcount = wordList.stream().collect(Collectors.toConcurrentMap(w->w.substring(0,1), w -> w.length(), Integer::sum));
            System.out.println(wordcount);
            
        }
        
        catch (IOException e)
        {
            System.out.println("File: " + filename + " not found");
        }
                    
  return wordcount; 
}

回答

你快到了。

您可以尝试以下方法。

  • 我们按单词的第一个字符分组,转换为小写。这让我们收集到一个Map<Character, …>,其中键是每个单词的第一个字母。一个典型的地图条目看起来像

    a = [ Apple, arrow, are ]
    
    a = [ Apple, arrow, are ]
    
  • 然后,使用该averagingDouble方法计算每组字长的平均值。一个典型的地图条目看起来像

    a = 4.33333333
    

这是代码:


请注意,为简洁起见,我省略了其他内容,例如null检查、空字符串和Locales。

另请注意,响应下面 Olivier Grégoire 和 Holger 的评论,此代码得到了很大改进。


以上是如何使用JavaStream查找共享键的所有值的平均值?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>