Monday, November 18, 2013

Java HshMap using StringTokenizer

Write a program that gets an array of words and does the following:

  • Prints each word and it's frequency
  • Prints only the words
  • Prints only the frequency of all words

Here's a sample run assuming the array of words as {i , came , i , saw , i , conquered}
came : 1
conquered : 1
i : 3
saw : 1
[came, conquered, i, saw]
[1, 1, 3, 1]

Note: Print in the same order as shown above.

SOLUTION: 

import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;

public class HashMapExample {

 public static void main(String[] args){
  //Scanner object
  Scanner input = new Scanner(System.in);
  //Reading the line
  System.out.print("Enter the line of words: ");
  String line = input.nextLine();
  //Creating String tokenizer for line
  StringTokenizer tokenizer = new StringTokenizer(line);
  
  //Creating and Adding words to the map
  int count=0;
  String word;
  Map< String,Integer > map = new HashMap< String,Integer >();
  
  while( tokenizer.hasMoreTokens() ) {
   word = tokenizer.nextToken();
   if(map.containsKey(word)){
    count = map.get(word);
    map.put(word, count+1);
   }
   else{
    map.put(word, 1);
   }
  }//End map creator
  
  //Creating set for the map
  Set< String > list = map.keySet();
  TreeSet< String > sortedList = new TreeSet< String >(list);
  
  //Printing duplicate words with frequency
  for ( String word2 : sortedList ) {
   System.out.printf("%s : %s\n",word2,map.get(word2));
  }
  //Printing only the words
  System.out.println(sortedList);
  //Printing only frequency
  System.out.print("[ ");
  for ( String word2 : sortedList ) {
   System.out.print(map.get(word2)+ " ");
  }
  System.out.println("]");
 }//End main method
}//End class

No comments:

Post a Comment