我在尝试平均 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/