Saturday, November 16, 2013

Java HsahMap (Collection) example

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

  • Prints out any duplicate words
  • Prints the number of distinct words
  • Prints the list of the words with duplicates eliminated.

Eg: if the input array = i came i saw i conquered then outputs are

  • Duplicate present: i
  • Number of distinct elements: 4
  • Distinct elements: [saw, came, conquered, i]

SOLUTION: 

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

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();
  //Printing duplicate words
  System.out.print("Duplicate words: ");
  
  for ( String word2 : list ) {
   if(map.get(word2)>1)
    System.out.print(word2+ " ");
  }
  
  //Printing the distinct elements
  System.out.println("\nNumber of Distinct elements: "+map.size());
  //Printing Distinct elements
  System.out.print("Distinct elements: ");
  System.out.println(list);
 }//End main method
}//End class

No comments:

Post a Comment