Hello I'm trying to read a file (words.txt), which contains a large list of english words into a Hashmap. I'm accessing the file with Paths. My function passes in a Path that is being opened and attempts to input the contents into a HashMap. I can print all the values of the Path word by word, but I'm having trouble storing the values into a HashMap. I'm attempting to make a SpellChecker thats better than my O(n) ArrayList implementation. Before I attempt to solve it with a Trie or BKTree, I would like to solve it with a HashMap.
Summary: How can I get the word.txt file opened with Path into a 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();
}
}
System.out::println
is a method reference and theWords.put(count++, stream)
is not. Additionally as already pointed out by Boris the stream would be added to the map, not the individual words.
A correct lambda expression could look like word -> theWords.put(count++, word)
but this also won't compile due to the count
variable not being effectively final, it cannot be changed inside a lambda expression.
If the intention is to be able to just quickly look up if a particular word is contained in the dictionary file a Set
would also be sufficient and the code could look like:
HashSet<String> theWords = Files.lines(dictFile)
.collect(Collectors.toCollection(HashSet::new));
Then look up words using eg
theWords.contains("hello");
For case insensitive lookups use () -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER)
instead of HashSet::new
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.