Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

--------------------------------------------------------------------------------

ID: 3835354 • Letter: #

Question

----------------------------------------------------------------------------------

sample.csv (Sample input file)

----------------------------------------

1 Overview This assignment is about hash tables. Unlike the previous assignments, you do not have to imple- ment your own data structures. Instead, you are required to use the data structures provided by Java. Specifically, the map data structures provided by Java. These are very similar to the hash tables we have studied in class. You will be using these data structures to load data and provide it back in a form requested by the program user 2 Tasks 2.1 Static Use of Maps in Java Create a class called FileToMapLoader. This class should be able to read a file, where each line has two comma-separated values. The first value is a person's name and the second is a phone number. You can use the sample file sample.csv provided with this assignment This class should have the following constant public static final String FILEPATH absolute path of file If should also have a mested static enum called Order, with three values: NAME, PHONE, and ORIGINAL. Finally, you must have a main method in this class which does the following (i) Loads the data from the file into a map provided by Java (i.e., a class that implements the java util. Map interface. (ii) Asks the user to specify one of the three orderings "name "phone", or original (iii) Prints the data in the order specified by the user. The "name" and "phone" options should print out the lines in ascending order of the names or phone numbers, respectively. The "original option should simply print the data in the same order as the input file So, this sounds just like another sorting assignment? Except for one little thing you are NOT allowed to use any explicit sorting. You can assume that the names are unique and every person has only one phone number. Also you can assume that no two people have the same phone number. The prog for this is very simple, but you have to read up on the different types of maps provided by Java to print the correct output. For this, consult http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html The entire assignment hinges on your understanding of Java's maps and how to use them. In one of the three orderings, you will have to write a comparator

Explanation / Answer

Hi,

Please see belwo the class and sample outputs:

FileToMapLoader.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;


public class FileToMapLoader {
   public static final String FILEPATH ="sample.csv";

   public enum Order {
       NAME,
       PHONE,
       ORIGINAL;
   }
   public static void readFile( Map<String, String> dataMap){
       BufferedReader br = null;
       FileReader fr = null;

       try {

           fr = new FileReader(FILEPATH);
           br = new BufferedReader(fr);
           String sCurrentLine;

           while ((sCurrentLine = br.readLine()) != null) {
               String [] input= sCurrentLine.split(",");
               dataMap.put(input[0], input[1]);
               System.out.println(sCurrentLine);
           }

       } catch (IOException e) {

           e.printStackTrace();

       }
   }

   private static HashMap sortByValues(Map<String, String> dataMap) {
       LinkedList list = new LinkedList(dataMap.entrySet());
       // Defined Custom Comparator here
       Collections.sort(list, new Comparator() {
           public int compare(Object o1, Object o2) {
               Entry entry1 =( Map.Entry)o1;
               Entry entry2 =( Map.Entry)o2;
              
               Integer val1 =Integer.valueOf(entry2.getValue().toString());
               Integer val2 =Integer.valueOf(entry2.getValue().toString());
               if( val1 > val2){
                   return 1;
               }
               else if( val1 < val2){
                   return -1;
               }
               else{
                   return 0;
               }
           }
       });
       // Here I am copying the sorted list in HashMap
       // using LinkedHashMap to preserve the insertion order
       HashMap sortedHashMap = new LinkedHashMap<>();
       for (Iterator it = list.iterator(); it.hasNext();) {
           Map.Entry entry = (Map.Entry) it.next();
           sortedHashMap.put(entry.getKey(), entry.getValue());
       }
       return sortedHashMap;
   }
   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       Map<String, String> dataMap = new HashMap<>();
       readFile(dataMap);
       System.out.println("Please specify one of the ordering: 1. "+Order.NAME+
               " 2. "+Order.PHONE+" 3. "+Order.ORIGINAL+" ");
       String order = scan.nextLine();

       if("1".equalsIgnoreCase(order)){
           Map<String, String> map = new TreeMap<String, String>(dataMap);
           System.out.println("After Sorting:");
           Set<Entry<String, String>> set2 = map.entrySet();
           Iterator iterator2 = set2.iterator();
           while(iterator2.hasNext()) {
               Map.Entry me2 = (Map.Entry)iterator2.next();
               System.out.print(me2.getKey() + ": ");
               System.out.println(me2.getValue());
           }
       }
       else if("2".equalsIgnoreCase(order)){
           Map<Integer, String> map = sortByValues(dataMap);
           System.out.println("After Sorting:");
           Set set2 = map.entrySet();
           Iterator iterator2 = set2.iterator();
           while(iterator2.hasNext()) {
               Map.Entry me2 = (Map.Entry)iterator2.next();
               System.out.print(me2.getKey() + ": ");
               System.out.println(me2.getValue());
           }
       }
       else if("3".equalsIgnoreCase(order)){
           Map<Integer, String> map = sortByValues(dataMap);
           System.out.println("After Sorting:");
           Set set2 = map.entrySet();
           Iterator iterator2 = set2.iterator();
           while(iterator2.hasNext()) {
               Map.Entry me2 = (Map.Entry)iterator2.next();
               System.out.print(me2.getKey() + ": ");
               System.out.println(me2.getValue());
           }
       }
   }


}

sample.csv

Kevin,624564343
Allen,644565354
Harry,614564353

Sample output 1:

1. NAME
2. PHONE
3. ORIGINAL

1
After Sorting:
Allen: 644565354
Harry: 614564353
Kevin: 624564343


Sample output 2:

Kevin,624564343
Allen,644565354
Harry,614564353
Please specify one of the ordering:
1. NAME
2. PHONE
3. ORIGINAL

2
After Sorting:
Harry: 614564353
Kevin: 624564343
Allen: 644565354

Sample output 3:

Kevin,624564343
Allen,644565354
Harry,614564353
Please specify one of the ordering:
1. NAME
2. PHONE
3. ORIGINAL

3
After Sorting:
Harry: 614564353
Kevin: 624564343
Allen: 644565354

Please see the WordCounter class below:

WordCounter.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;


public class WordCounter {
   public static String FILEPATH ="input_file.txt";
   public static void main(String [] args){
       Scanner scan = new Scanner(System.in);
       //Reading the frile name from user
       System.out.println("Please enter the file name");
       String FILEPATH= scan.nextLine();
      
       HashMap<String, Integer> wordCountMap = readFromFile();
       display(wordCountMap);
   }
  
   /**
   * Reading the component measures from file
   * @return
   */
   public static HashMap<String, Integer> readFromFile(){
       BufferedReader br = null;
       FileReader fr = null;
       String currString ="";
       //Creating a HashMap to count words
       HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
       try {

           fr = new FileReader(FILEPATH);
           br = new BufferedReader(fr);

           String sCurrentLine;


           while ((sCurrentLine = br.readLine()) != null) {
               StringTokenizer tkens = new StringTokenizer(sCurrentLine);
               while(tkens.hasMoreTokens()){
                   currString = tkens.nextToken();
                   if(wordCount.containsKey(currString)){
                       wordCount.replace(currString, wordCount.get(currString)+1);
                   }
                   else{
                       wordCount.put(currString, 1);
                   }
               }
              
           }

       } catch (IOException e) {

           e.printStackTrace();

       }
      
       return wordCount;
   }
  
   /**
   * To print the items in Map
   * @param wordMap
   */
   public static void display(HashMap<String, Integer> wordMap){
       //loop a Map
       for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {
           System.out.println( entry.getKey() + " " + entry.getValue());
       }
   }

}

input_file.txt

I am stuck Why I am stuck

Sample output:

Please enter the file name
currString
stuck    2
I 2
Why    1
am 2