Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use keySet() to retrieve a set of keys within a HashMap, loop over it and find its count for each key?

Tags:

java

keyset

I am nearing the end of my assignment and one of the last thing that I have been instructed t do is to:

  • Use keySet() to retrieve the set of keys (the String part of the mapping). Loop over this set and print out the word and its count.

I have used the keySet() method to print out the number of keys within my HashMap, but what I have not done yet is find the length for each word within the HashMap and then print out the number of characters within each word. I am currently unsure as to how I should do this. I'm assuming I would use some time of for loop to iterate through the keySet() which I have already done and then use something like a .length() method to find out the length of each word and then print it out somehow?

Here is my relevant code so far:

Main class

package QuestionEditor;
import java.util.Set;
public class Main{
    public static void main (String[] args) {
        WordGroup secondWordGroup = new WordGroup ("When-you-play-play-hard-when-you-work-dont-play-at-all");


         Set<String> set = secondWordGroup.getWordCountsMap().keySet();

         System.out.println("set : " + set + "\n");

         for(String key : set)
         {
             System.out.println(key);
         }
        }
    }

WodGroup class

package QuestionEditor;
import java.util.HashMap;

public class WordGroup {

    String  word;

    // Creates constructor which stores a string value in variable "word" and converts this into lower case using
    // the lower case method.
    public WordGroup(String aString) {

        this.word = aString.toLowerCase();
    }

    public String[] getWordArray() {

        String[] wordArray = word.split("-");
        return wordArray;
    }

    public HashMap<String, Integer> getWordCountsMap() {

        HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();

        for (String word : this.getWordArray()) {
            if (myHashMap.keySet().contains(word)) {
                myHashMap.put(word, myHashMap.get(word) + 1);
            } else {
                myHashMap.put(word, 1);
            }

        }

        return myHashMap;
    }   
}

Any help on how to do this would be greatly appreciated, thanks.

UPDATE So when my code compiles, I am getting the output:

Key: play has 3 counter
Key: all has 1 counter
Key: at has 1 counter
Key: work has 1 counter
Key: hard has 1 counter
Key: when has 2 counter
Key: you has 2 counter
Key: dont has 1 counter

But what I actually want it to do is to print out the amount of characters within each word. So for example, play would count 4 times, all would count 3 times, at would count 2 times etc. Any ideas on how to implement this?

like image 334
Alan Avatar asked Nov 12 '16 20:11

Alan


People also ask

How do I iterate through a HashMap using keySet?

If you're only interested in the keys, you can iterate through the keySet() of the map: Map<String, Object> map = ...; for (String key : map. keySet()) { // ... }

What is keySet () in Java?

The Java HashMap keySet() method returns a set view of all the keys present in entries of the hashmap. The syntax of the keySet() method is: hashmap.keySet() Here, hashmap is an object of the HashMap class.

How do I get the value of a map using keySet?

in your current code, you are doing the following: for (String dog: data. keySet()) { // use the dog String race = data. get(dog); // this will give the value of race for the key dog // using dog to do fetch details from site... }


2 Answers

The part that you are probably missing is: you can use the keys to then access your map values, like this:

Map<String, Integer> whateverMap = ... coming from somewhere

for (String key : whateverMap.keySet()) {
  Integer countFromMap = whateverMap.get(key);
  System.out.println("Key: " + key + " has " + countFromMap + " counter");

The above is meant as example to get you going, I didn't run it through a compiler.

My point here: there are various ways to iterate the elements you stored within a Map. You can use entrySet() to retrieve Entry objects; or you iterate the keys, and lookup values using each key.

like image 166
GhostCat Avatar answered Sep 21 '22 21:09

GhostCat


You can use stream API from Java 8 to create a Map<String,Integer>

Map<String, Integer> stringIntegerMap = set.stream().collect(HashMap::new,
    (hashMap, s) -> hashMap.put(s, s.length()), HashMap::putAll);

stringIntegerMap.forEach((key,value) ->System.out.println(key + " has length: "+key.length() + " and count: "+value));

The second parameter to collect function is an accumulator. You are accumulating a hasmap of your string from keyset and it's length

like image 26
bhavya.work Avatar answered Sep 19 '22 21:09

bhavya.work