您好我正在尝试读取一个文件(words.txt),其中包含大量英文单词到Hashmap中。我正在使用Paths访问该文件。我的函数传入正在打开的Path并尝试将内容输入到HashMap中。我可以逐字打印Path的所有值,但是我将这些值存储到HashMap中时遇到了问题。我试图让SpellChecker比我的O(n)ArrayList实现更好。在我尝试使用Trie或BKTree解决它之前,我想用HashMap解决它。
总结:如何将使用Path打开的word.txt文件放入HashMap。
private static void createMap(Path dictFile) throws Exception{
Map<Integer,String> theWords = new HashMap<>();
int count = 0;
try (Stream<String> stream = Files.lines(dictFile)) {
stream.forEach(theWords.put(count++, stream));
//stream.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
System.out::println
是方法参考,theWords.put(count++, stream)
不是。另外正如鲍里斯已经指出的那样,流将被添加到地图中,而不是单个词。
正确的lambda表达式可能看起来像word -> theWords.put(count++, word)
,但由于count
变量不是有效的最终版本,因此也无法编译,不能在lambda表达式中更改。
如果意图是能够快速查找字典文件中是否包含特定单词,Set
也就足够了,代码可能如下所示:
HashSet<String> theWords = Files.lines(dictFile)
.collect(Collectors.toCollection(HashSet::new));
然后使用例如查找单词。
theWords.contains("hello");
对于不区分大小写的查找,请使用() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)
而不是HashSet::new
。