【问题标题】:Return a Stream of Strings from a Path located in a HashMap从位于 HashMap 中的路径返回字符串流
【发布时间】: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


【解决方案1】:

你有两个问题:

1 - 在地图中迭代使用

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

2 - Files.readAllBytes 将读取一个字符串中的所有文件。所以如果你有 foo 和 bar 这两个词,当你用这个函数阅读时,你会得到:foobar。

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

【讨论】:

    猜你喜欢
    • 2012-01-12
    • 2020-10-31
    • 2016-10-27
    • 2015-07-27
    • 2014-06-07
    • 1970-01-01
    • 2020-05-23
    • 2020-11-27
    • 2016-11-23
    相关资源
    最近更新 更多