How to cycle through each item in a hashmap using a while loop

Charlie :

I am creating a piece of code to take a hashmap called wordFrequencies, which contains some words and how many times they appear in a given string.

To spare details, the words need to line up so I am trying to create code to add spaces to the start of the words until they are all in alignment. I am doing this by comparing their lengths.

The issue I am having is with the while loop, as word is defined only in the for loop and I am not sure how to define it to be used within the while loop, as there is know such thing as a "while each" loop.

  // 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
        }
HomeIsWhereThePcIs :

You just need to loop through the set again.

The problem with doing this in a loop: word = " " + word; is that it is not efficient to concatenate strings in loops using the + operator . On Java 11+ you can use String repeat(int count) to get the spaces. On Java 8 you can use StringBuilder append(String str) in a loop to get the spaces.

Also you cant edit the keys in the HashMap. You can remove one entry and add a new one, but it would be better to use a function to format the words for output.

Here is an example

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;
}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194152&siteId=1