Home > Net >  Count how many times a word occurs in a HashMap per key
Count how many times a word occurs in a HashMap per key

Time:11-01

I have a HashMap in which sentence records are stored with an associated key. Now, an output should be created in this displayed how much the word (in my example the word "car") in this index (key) occurs. For example, if the word "car" occurs in the index (key) 5, 4 times, the 5 should also be output 4 times.

The current output is: Car : [1, 2, 3, 5]

My desired output is: Car : [1, 1, 2, 3, 3, 5, 5, 5, 5]

Map<Integer, String> carHashMap = new HashMap<>();
ArrayList<Integer> showCarsInMap = new ArrayList<>();

carHashMap.put(1, "this car is very fast car");
carHashMap.put(2, "i have a old car");
carHashMap.put(3, "my first car was an mercedes and my second car was an audi");
carHashMap.put(4, "today is a good day");
carHashMap.put(5, "car car car car");

for (Map.Entry<Integer, String> entrySection : carHashMap.entrySet()) {

    if (entrySection.getValue().contains("car")) {

        showCarsInMap.add(entrySection.getKey());

    }
}

System.out.println("Car : "   showCarsInMap);
    

I guess I have to add an additional if-loop, but I don't know how my program can recognize which "car" has already been counted and which not.

CodePudding user response:

I suggest you simply use regex for this:

for (Map.Entry<Integer, String> entrySection : carHashMap.entrySet()) {
     Pattern p = Pattern.compile("(?:^|\\W)car(?:$|\\W)"); //This will only capture the exact word, as dicussed in the comments.
     Matcher m = p.matcher(entrySection.getValue());
     while (m.find()) {
           showCarsInMap.add(entrySection.getKey());
     }
}

Regex is from here.

CodePudding user response:

Though not ideal but this will work:

carHashMap.entrySet().stream().forEach(x -> {
            long count = Arrays.stream(x.getValue().split(" ")).filter(t -> t.equalsIgnoreCase("car")).count();
            while (count-- > 0) {
                showCarsInMap.add(x.getKey());
            }
        });

Here, I am considering you are only going to have space(" ") as a separator. Also, you don't need to use for loop but you can use streams directly on hashmap.

  • Related