我想找到文件中所有单词的集合。应该对这个集合进行排序。 大小写无关紧要。 这是我的方法:
public static Set<String> setOfWords(String fileName) throws IOException {
Set<String> wordSet;
Stream<String> stream = java.nio.file.Files.lines(java.nio.file.Paths.get(fileName));
wordSet = stream
.map(line -> line.split("[ .,;?!.:()]"))
.flatMap(Arrays::stream)
.sorted()
.map(String::toLowerCase)
.collect(Collectors.toSet());
stream.close();
return wordSet;
}
测试文件:
这是一个文件 五行。它有两个句子, 并包含word文件 在此文件的多行中。 该文件可用于测试?
打印集合时,我得到以下输出:
Set of words:
a
be
in
sentences
testing
this
for
multiple
is
it
used
two
the
can
with
contained
file
and
of
has
lines
five
word
谁能告诉我,为什么集合没有按照自然顺序(对于字符串词典)排序?
提前致谢
最佳答案
您可以使用像 TreeSet
这样的排序集合,使用 String.CASE_INSENSITIVE_ORDER
作为 Comparator
Set<String> set = stream
.map(line -> line.split("[ .,;?!.:()]"))
.flatMap(Arrays::stream)
.collect(Collectors.toCollection(()-> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)));
或者您可以使用不区分大小写的比较器对元素进行排序,并将其收集到维护插入顺序的集合中。
List<String> list = stream
.map(line -> line.split("[ .,;?!.:()]"))
.flatMap(Arrays::stream)
.sorted(String::compareToIgnoreCase)
.distinct()
.collect(Collectors.toList());
关于java - 字符串流未排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36966150/