【问题标题】:How to iterate through a HashSet and return the set with qualified elements?如何遍历 HashSet 并返回具有限定元素的集合?
【发布时间】:2017-02-07 06:36:39
【问题描述】:

我正在尝试从包含 500,000 个英文单词的文本文件中读取并将其存储到 HashSet 以用于性能目的。然后我想返回一个包含限定元素的HashSet,例如,5个字母的单词,6个字母的单词等等。

到目前为止,这是我的代码,我不知道该怎么做。 感谢您的解决方案!

 private static HashSet<String> readPuzzleFile(int wordLength) {
        HashSet<String> unProcessedPuzzle = new HashSet<String>();
        try (Scanner file = new Scanner(new File(PATHTOPUZZLE))) {
            while (file.hasNextLine()) {
                unProcessedPuzzle.add(file.nextLine());
            }
        } catch (FileNotFoundException e) {
            System.out.println("No Puzzle File Found!");
            return null;
        }
        HashSet<String> puzzle = new HashSet<String>();
        Iterator iterator = unProcessedPuzzle.iterator();
        for (String word : unProcessedPuzzle){
            puzzle.addAll(word);
        }
       }

【问题讨论】:

  • 你的问题是什么?
  • @IQV 只是怎么做,抱歉忘了第一次把它放在问题中。
  • 怎么办?
  • 这听起来像是流或 Groovy 迭代器方法的教科书案例。
  • @TianchengXu 如果您按照下面的评论建议解决了这个问题,请关闭问题或发布并接受您的回答。

标签: java loops hash iterator hashset


【解决方案1】:
private static HashSet<String> readPuzzleFile(int wordLength) {
        HashSet<String> unProcessedPuzzle = new HashSet<String>();
        try (Scanner file = new Scanner(new File(PATHTOPUZZLE))) {
            while (file.hasNextLine()) {
                unProcessedPuzzle.add(file.nextLine());
            }
        } catch (FileNotFoundException e) {
            System.out.println("No Puzzle File Found!");
            return null;
        }
        HashSet<String> puzzle = new HashSet<String>();
        Iterator iterator = unProcessedPuzzle.iterator();
        for (String word : unProcessedPuzzle){
            puzzle.add(word); //........addAll -> add.........
        }
        return puzzle;//........return puzzle.........
       }

【讨论】:

  • 虽然这不是正确的方法,但你启发了我。现在我解决了,谢谢!
猜你喜欢
  • 2018-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多