Saturday, November 16, 2013

Java Map Example

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}

  • saw : 1
  • came : 1
  • conquered : 1
  • i : 3
  • [sa, cam, cons, i]
  • [1, 1, 1, 3]

Note: Order doesn't matter in any of the above outputs.

SOLUTION: 

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

public class MapExample {

 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();
  //Printing duplicate words with frequency
  for ( String word2 : list ) {
   System.out.printf("%s : %s\n",word2,map.get(word2));
  }
  
  //Printing only the words
  System.out.println(list);
  //Printing only frequency
  System.out.print("[ ");
  for ( String word2 : list ) {
   System.out.print(map.get(word2)+ " ");
  }
  System.out.println("]");
 }//End main method
}//End class

No comments:

Post a Comment