Question: Rewrite the program below so that reads from a text file and then counts the number of occurences of each letter in a string. The
Rewrite the program below so that reads from a text file and then counts the number of occurences of each letter in a string. The program displays the letters in ascending order.
You should provide two methods. Each method that has an argument of map collection.// (textfile.txt contains the string: Welcome to CECS)The output should look like this:
Enter the text file to read from: textfile.txt
Map contains: Sort by keys Key Value c 3 e 3 l 1 m 1 o 2 s 1 t 1 w 1
Sort by values Key Value c 3 e 3 o 2 l 1 m 1 s 1 t 1 w 1
=================================================================================================================================================
Here is the program with the data manually inputed:
import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeMap;
public class MapSorting {
public static void sortByKey(Map
System.out.println("Sort by keys");
System.out.println("Key\tValue");
Map
Iterator
while(itr.hasNext()) {
Entry
System.out.println(entry.getKey()+"\t"+entry.getValue());
}
}
public static void sortByValue(Map
System.out.println("Sort by values");
System.out.println("Key\tValue");
List
Comparator
@Override
public int compare(Entry
return object1.getValue().compareTo(object2.getValue());
}
};
Collections.sort(list, comparator);
for(int i=list.size()-1;i>=0;i--) {
Entry
System.out.println(entry.getKey()+"\t"+entry.getValue());
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String line = scanner.nextLine();
line = line.toLowerCase();
char c;
Map
for(int i=0;i c = line.charAt(i); if(c==' ') { continue; } if(map.containsKey(c)) { map.put(c, map.get(c)+1); }else { map.put(c, 1); } } System.out.println("Map contains:"); sortByKey(map); sortByValue(map); scanner.close(); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
