java - 如何使用 Java Stream 查找共享键的所有值的平均值?

标签 java java-stream

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

"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, …> ,其中键是每个单词的第一个字母。一个典型的 map 条目看起来像
    a = [ Apple, arrow, are ]
    
  • 然后,计算每组字长的平均值,使用averagingDouble方法。一个典型的 map 条目看起来像
    a = 4.33333333
    

  • 这是代码:
    // groupingBy and averagingDouble are static imports from
    // java.util.stream.Collectors
    Map<Character, Double> map = Arrays.stream(str.split(" "))
        .collect(groupingBy(word -> Character.toLowerCase(word.charAt(0)),
            averagingDouble(String::length)));
    

    请注意,为简洁起见,我省略了其他内容,例如 null检查、空字符串和 Locale s。
    另请注意,此代码已根据 Olivier Grégoire 和 Holger 的评论进行了重大改进。

    关于java - 如何使用 Java Stream 查找共享键的所有值的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65287747/

    相关文章:

    java - Gradle 放弃我使用 IntelliJ 设置的源路径

    java - 我遇到的最奇怪的 Java 问题,NoClassDefFoundError 由于注释?

    java - spring-boot Amazon Elastic Beanstalk 忽略 'SPRING_APPLICATION_JSON'

    java - 并行流与串行流

    java - 纳秒和毫秒

    java - 将 linkedList 转换为数组列表时出现 ArrayIndexOutOfBoundsException

    java - Java 中并行流的实用用例有哪些?

    java - map <X, map <Y, Z> 到 map <Y, map <X, Z>

    java - SortedSet.stream() 上的 findFirst()

    java - StreamEx 分组为列表返回不正确的记录数