CodeMonkey
CodeMonkey

Reputation: 2295

Insertion into Hash Map data structure JAVA

I am using a program to read keywords in a file and sort them on basis of frequency. I am using Map data structure for the same. But i am facing problem, even if i have repeated entries, their count is not increased. Thus if a word is repeated in the file it is stored in a different place in the data structure rather than incrementing value of the previous entry in the maps. Please find my code below. That is what i tried. Also i am making sure if a match is "" or " " it is not stored in the hash map still it is counted.

Pattern p = Pattern.compile("[a-zA-Z]*",Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(handlerContent);
    while(m.find() ) //&& (m.group().length()>1)
    {
         boolean blnExists = keyword_counts.containsValue(m.group());
         if(blnExists==true)
         {
             if(m.group()!="" || m.group()!=" ")
             {
                 System.out.println("Repeat");
                 keyword_counts.put(m.group(), keyword_counts.get(m.group()+1));
                 System.out.println(m.group()+" "+keyword_counts.get(m.group()) );
             }
         }
         else
         {
             if(m.group()!="" || m.group()!=" ")
             {
                 keyword_counts.put(m.group(), 1);
                 System.out.println(m.group()+" "+keyword_counts.get(m.group()) );
             }
         }                  
    }

Upvotes: 0

Views: 470

Answers (3)

in your statement boolean blnExists = keyword_counts.containsValue(m.group()); you are check for the value instead of the key.

try this:

boolean blnExists = keyword_counts.containsKey(m.group());

and use if(m.group() != null && !"".equals(m.group().trim())) instead of

if(m.group()!="" || m.group()!=" ")

Upvotes: 1

jcomeau_ictx
jcomeau_ictx

Reputation: 38482

in Java "=" should not be used with strings. use the "equals" method instead.

Upvotes: 1

assylias
assylias

Reputation: 328735

Your test should probably be:

 keyword_counts.containsKey(m.group());

And you should use equals to compare strings instead of == or != but that is not the reason for your issue.

Upvotes: 1

Related Questions