【问题标题】:How to cycle through each item in a hashmap using a while loop [duplicate]如何使用while循环循环遍历哈希图中的每个项目[重复]
【发布时间】:2020-06-22 20:07:22
【问题描述】:

我正在创建一段代码来获取名为 wordFrequencies 的哈希图,其中包含一些单词以及它们在给定字符串中出现的次数。

为了节省细节,单词需要对齐,所以我尝试创建代码以在单词的开头添加空格,直到它们全部对齐。我通过比较它们的长度来做到这一点。

我遇到的问题是 while 循环,因为 word 仅在 for 循环中定义,我不知道如何定义它以在 while 循环中使用,因为知道诸如“while”之类的东西每个”循环。

  // loop to determine length of longest word

        int maxLength = 0;

        for (String word : wordFrequencies.keySet()){
            if (word.length() > maxLength) {
                maxLength = word.length();
                }
            }

        // loop to line up the words in the graph / table

        while (word.length() < maxLength){
            word = " " + word;   // if word is shorter than longest word, add spaces to the start until they line up
        }

【问题讨论】:

  • @xerx593 是的。我需要在单词的开头添加空格,直到与最长单词的长度相同。 for 循环处理确定最长单词的长度,但它是我正在努力解决的 while 循环
  • 您可能想要使用 String.format() ,它使用 printf 格式并且可以左右对齐值。

标签: java loops hashmap


【解决方案1】:

你只需要再循环一次。

在循环中执行此操作的问题是:word = " " + word;it is not efficient to concatenate strings in loops using the + operator 。在 Java 11+ 上,您可以使用 String repeat(int count) 来获取空格。在 Java 8 上,您可以在循环中使用 StringBuilder append(String str) 来获取空格。

您也不能编辑 HashMap 中的键。您可以删除一个条目并添加一个新条目,但最好使用函数来格式化输出的单词。

这是一个例子

public class scratch {
 public static void main(String[] args) {
    int maxLength = 0;
    HashMap<String, Integer> wordFrequencies = new HashMap<>();
    wordFrequencies.put("bla", 0);
    wordFrequencies.put("blaaaa", 0);
    wordFrequencies.put("blaaaaaaaaaaaaaaaa", 0);

    for (String word : wordFrequencies.keySet()) {
        if (word.length() > maxLength) maxLength = word.length();
    }

    for (String word : wordFrequencies.keySet()) {
        System.out.println(addSpace(word, maxLength));
    }

 }

 public static String addSpace(String word, int maxLength) {
    StringBuilder newWord = new StringBuilder();
    for (int i = 0; i < maxLength - word.length(); i++) {
        newWord.append(" ");
    }
    return newWord.append(word).toString();

    // On Java 11+ you can use String repeat(int count)
    //return " ".repeat(maxLength - word.length()) + word;
}

}

【讨论】:

  • String 类型的方法 repeat(int) 未定义
  • @Charlie 对不起,我忘记了 String.repeat() 在 Java 8 中不可用。我已经更新了我的答案,改为使用 StringBuilder。
【解决方案2】:

主要问题:word 在此范围内不可见 - 解决方案:您必须迭代一次才能找到 maxLength,然后再迭代一次以格式化“密钥”。此外,我不会修改输入键,而是返回“格式化副本”,如下所示:

int maxLength = Integer.MIN_VALUE;
for (String word : wordFrequencies.keySet()){
  if (word.length() > maxLength) {
    maxLength = word.length();
  }
}

// a new set for formatted words:
Set<String> formatted = new Set<>(wordFrequencies.size());
// repeat the above loop:
for (String word : wordFrequencies.keySet()){
    // (unfortunately), You have to nest the loop & spend 1 variable:
    String fWord = word;
    while (fWord.length() < maxLength){
        fWord = " " + fWord;   // string concatenation is considered "badong" (bad & wrong)
    }
    // now "put it in the case":
    formatted.add(fWord);
}

// return formatted;

String +:How can I pad a String in Java?更好的方法

【讨论】:

  • '我不会修改输入键,而是返回“格式化副本”'。你能解释一下为什么吗?
  • 另外,一个词不能否定,为什么要使用MIN_VALUE?
  • 因为,尤其是在上下文很少的情况下:它(输入)来自哪里?以后谁会(想要)使用它? ..而且因为它在技术上更简单;)
  • MIN_VALUE (它是可能的最低 int 值,因此“始终”是 find-max 算法的故障安全初始化)..0 在您的情况下就足够了,但有一个“空单词列表” ..输出(findMaxLenght)将与“仅填充 0-legth-words 的列表”相同 ...-1 suffcient。
  • 如果您想修改输入映射:Changing HashMap keys during iteration;)(也只能通过临时副本)
猜你喜欢
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
相关资源
最近更新 更多