【发布时间】:2017-07-03 07:07:57
【问题描述】:
我正在尝试了解流和路径。我在 O(n) 时间内创建了一个拼写检查器,我正在尝试遵循使用 Map / HashMap / Paths / 和 Streams 创建拼写检查器的指南。
我已经创建了我的 word 文件的路径并将其加载。我无法理解如何打印此列表。从路径读取时,我似乎无法访问它创建的单词列表。我相信我必须返回一个字符串流,只是无法弄清楚这到底是如何工作的。
输入文件是一个单词字典,大约 56k 个单词。每行一个字。
样本输出(一长串单词)
aardvarkaardwolfaaronabackabacusabaftabaloneabandonabandonedabandonmentabandonsabaseabasedabasementabashabashedabateabatedabatementabatesabattoirabattoirsabb
当前代码
import java.io.*;
import java.util.*;
import java.util.Scanner;
import java.lang.*;
import java.nio.file.*;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.*;
public class TheChecker {
private static Map<String,Integer> dict = new HashMap<>();
public static void main(String[] args) {
Path dictOpen = Paths.get("/Users/sam/IdeaProjects/wordSpell/src/newWords.txt");
try{
//try opening file
Spelling(dictOpen);
} catch(Exception e) {
System.out.println("Failed path");
}
//fails to find dict even though I load it into memory the step before.
for(String temp : dict) {
System.out.println(temp);
}
//This produces one giant string of all words combined on one line.
//Ideally I would like to use the known word method to find a single word
for(String temp : dict.keySet() {
System.out.println(temp);
}
}
private static void Spelling(Path dictionaryFile) throws Exception{
Stream.of(new String(Files.readAllBytes( dictionaryFile )).toLowerCase().replaceAll("[^a-z ]","").split(" ")).forEach( (word) ->{
dict.compute( word, (k,v) -> v == null ? 1 : v + 1 );
});
}
private static Stream<String> known(Stream<String> words){
return words.filter( (word) -> dict.containsKey(word) );
}
}
【问题讨论】:
-
Map不是Iterable。也许你的意思是for(String temp : dict.keySet())? -
那么根据keySet或者Value打印出来?
-
我不明白这个问题。
-
如果我 system.out.println 基于 dic.keySet() - 我得到 1 个巨大的字符串输出。我正在尝试一次打印出每个单词。
-
这意味着你只有 1 把巨钥匙。你能包括一些示例输入吗?
标签: java path hashmap java-8 java-stream