我在尝试对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 ]
然后,使用该averagingDouble
方法计算每组单词长度的平均值。然后,典型的地图条目将看起来像
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
check,空字符串和Locale
s之类的其他内容。
另请注意,此代码在很大程度上响应了以下OlivierGrégoire和Holger的评论而得到了改进。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句