如何使用Lambda Expression获得单词平均长度 [英] How to get words average length using Lambda Expression
问题描述
我有一个单词列表文本文件,我想从该文件中获取最小,最大和平均单词长度。
I have a word list text file, I want to get min, max and average word lengths from that file.
我有一个流方法:
public static Stream<String> readWords(String filename) {
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
Stream<String> stringStream = reader.lines();
return stringStream;
} catch (IOException exn) {
return Stream.<String>empty();
}
}
在我的主要测试方法中,我打印最大值和min
In my main method for testing I'm printing max and min
System.out.println(readWords(filename)
.min(Comparator.comparing(s -> s.length()))
.get()
.length()
);
System.out.println(readWords(filename)
.max(Comparator.comparing(s -> s.length()))
.get()
.length()
);
它按预期工作。
问题:
是否有可能像我在min和max中那样获得字长的平均值?在是或否的情况下,如何做到(仅作为Lambda表达式)?
Questions:
Is it possible to get the average of the word length like I did in min and max? In both case yes or no, how to do that (only as Lambda Expression)?
推荐答案
lines()
方法将为您提供一行而不是单词。获得 Stream
后,请致电 flatMap
用字替换行,提供lambda表达式拆分单词:
The lines()
method will get you a stream of the lines, not the words. Once you have the Stream
, call flatMap
to replace the lines with the words, supplying the lambda expression to split out the words:
Stream<String> stringStream = reader.lines().flatMap( line ->
Stream.of(line.split("\\s+"))
);
这将纠正 max
的实施, 分钟
。它还会影响您希望实现的任何平均计算的正确性。
This will correct your implementation of max
and min
. It also affects the correctness of any average calculation you wish to implement.
要获得平均值,您可以调用 mapToInt
将单词流映射到它们的长度(产生 IntStream
),然后调用 平均
,其中返回 OptionalDouble
。
To obtain the average, you can call mapToInt
to map the stream of words to their lengths (yielding an IntStream
), then call average
, which returns an OptionalDouble
.
System.out.println(readWords(filename)
.mapToInt( s -> s.length() ) // or .mapToInt(String::length)
.average()
.getAsDouble());
这篇关于如何使用Lambda Expression获得单词平均长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!