1.

Write a Java Program to count the number of words in a string using HashMap.

Answer»

Answer:

Let’s write a program to count the word in a sentence using java HashMap an implementation class of Map.

Map is data structure which contains value based on key.

import java.util.*; // PACKAGE contains the collection classes. ex Map, HashMap, TreeSet etc

class WordCount {

public static VOID main(String args[]) {

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

Scanner sc = new Scanner(System.in); // used to read user input

System.out.println("Enter a string:");

String sentence = sc.nextLine();

String[] tokens = sentence.split(" "); // split based on space

for (String token: tokens) {

String word = token.toLowerCase();

if (map.containsKey(word)) {

int count = map.get(word); // get word count

map.put(word, count + 1); // override word count

} ELSE {

map.put(word, 1); // INITIAL word count to 1

}

}

//display the data

Set < String > keys = map.keySet(); // list of unique words because it's a Set

TreeSet < String > sortedKeys = new TreeSet < > (keys); // ASCENDING order of words

for (String str: sortedKeys) {

System.out.println("Word =" + str + " and it's count = " + map.get(str));

}

}

}JavaCopy



Discussion

No Comment Found