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 map) {

System.out.println("Sort by keys");

System.out.println("Key\tValue");

Map tree = new TreeMap<>(map);

Iterator> itr = tree.entrySet().iterator();

while(itr.hasNext()) {

Entry entry = itr.next();

System.out.println(entry.getKey()+"\t"+entry.getValue());

}

}

public static void sortByValue(Map map) {

System.out.println("Sort by values");

System.out.println("Key\tValue");

List> list = new LinkedList<>(map.entrySet());

Comparator> comparator = new Comparator>() {

@Override

public int compare(Entry object1, Entry object2) {

return object1.getValue().compareTo(object2.getValue());

}

};

Collections.sort(list, comparator);

for(int i=list.size()-1;i>=0;i--) {

Entry entry = list.get(i);

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 map = new HashMap<>();

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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!