jdalbey

Map driver

Nov 15th, 2013
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.Map;
  3. import java.util.HashMap;
  4.  
  5. /**
  6.  * java.util.Map driver
  7.  * Reads items to put in a Map from standard input,
  8.  * then reports the elapsed time and unique word count.
  9.  * @author jdalbey
  10.  */
  11. public class Mapdriver
  12. {
  13.     public static void main (String args[]) throws java.io.FileNotFoundException
  14.     {
  15.         Map<String,Integer> ht = new HashMap<String,Integer>();
  16.         Scanner in = new Scanner(System.in);
  17.         System.out.println("Enter a list of words (one per line), terminated by Ctrl-D");
  18.        
  19.         long start = System.currentTimeMillis();
  20.         int wordCount = 0;
  21.        
  22.         // Put all the words in the map
  23.         while (in.hasNext())
  24.         {
  25.             String word = in.next();
  26.             // If word doesn't exist in map, add it
  27.             if (!ht.containsKey(word))
  28.             {
  29.                ht.put(word,1);  
  30.                wordCount++;
  31.             }            
  32.         }
  33.         // compute elapsed time
  34.         long end = System.currentTimeMillis();
  35.         float secs = (end - start) / 1000f;
  36.         // show results
  37.         System.out.print("Took " + secs + " secs. "  );  
  38.         System.out.println("wordCount: " + wordCount);
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment