Tuesday, 10 August 2021

Frequency of Words using HashMap

 package JavaPracticeInterview;


import java.util.HashMap;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;


public class Frequency_of_Words {


public static void main(String[] args) {

// TODO Auto-generated method stub

String str ="Hello I am a programmer I am a hello";

String words[] = str.split(" ");

Map<String, Integer> map = new HashMap<String, Integer>();

for(String s: words) {

Integer count = map.get(s);

if(count==null) {

map.put(s, 1);

}

else  {

map.put(s, ++count);

}

}


Set<Entry<String, Integer>> entrySet = map.entrySet();

for(Entry<String, Integer> entry: entrySet) {

if(entry.getValue()>0) {

System.out.println(entry.getKey() + " " + entry.getValue());

}

}

}


}



o/p:
a 2
Hello 1
programmer 1
I 2
hello 1
am 2

No comments:

Post a Comment