从位于HashMap中的路径返回字符串流

时间:2017-02-14 20:25:20

标签: java path hashmap java-8 java-stream

我试图了解Streams和Paths。我在O(n)时间创建了一个拼写检查器,并且我试图遵循使用Map / HashMap / Paths /和Streams创建拼写检查器的指南。

我创建了一个指向我的word文件的路径并将其加载。我无法理解如何打印此列表。我似乎无法访问从Path中读取时创建的单词列表。我相信我必须返回一串字符串,只是很难弄清楚这是如何运作的。

输入文件是一个单词字典,大约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) );
    }
    }

1 个答案:

答案 0 :(得分:0)

你有两个问题:

1 - 对于地图中的迭代使用

for (Map.Entry<String, Integer> entry : dict.entrySet())
    {
        System.out.println(entry.getKey() + "/" + entry.getValue());
    }

2 - Files.readAllBytes将读取一个String中的所有文件。因此,如果你有foo和bar这两个词,当你用这个函数阅读时,你将拥有:foobar。

查找Files.readAllLines。 http://www.java2s.com/Tutorials/Java/java.nio.file/Files/Java_Files_readAllLines_Path_path_Charset_cs_.htm