Fix the code : use a text file to save data(the output should be saved into text file ! ) the code: AlphabetsSortByValueSortByKey.java import java.util.*;
Fix the code : use a text file to save data(the output should be saved into text file ! )
the code:
AlphabetsSortByValueSortByKey.java
import java.util.*;
import java.util.Map.Entry;
public class AlphabetsSortByValueSortByKey {
static Map < Character, Integer > m = new HashMap < Character, Integer > ();
public static void main(String[] args) {
// Declaring variables
String str;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
// Getting the input entered by the user
System.out.print("Enter the String :");
str = sc.nextLine();
char ch;
// Populating each character into the Map
for (int i = 0; i < str.length(); i++) {
ch=str.charAt(i);
if(Character.isAlphabetic(ch))
{
checkMap(Character.toLowerCase(ch));
}
}
Set < Entry < Character, Integer >> set = m.entrySet();
List < Entry < Character, Integer >> list = new ArrayList < Entry < Character, Integer >> (
set);
// Sorting based on values
Collections.sort(list, new Comparator < Map.Entry < Character, Integer >> () {
public int compare(Map.Entry < Character, Integer > o1,
Map.Entry < Character, Integer > o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
System.out.println("Map contains: ");
System.out.println("Sort by values ");
System.out.println("Key\tValue");
// Displaying the Key value Pairs
for (Map.Entry < Character, Integer > entry: list) {
System.out.println(entry.getKey() + " \t " + entry.getValue());
}
// Sorting based on keys
Collections.sort(list, new Comparator < Map.Entry < Character, Integer >> () {
public int compare(Map.Entry < Character, Integer > o1,
Map.Entry < Character, Integer > o2) {
return (o1.getKey()).compareTo(o2.getKey());
}
});
System.out.println("Sort by keys ");
System.out.println("Key\tValue");
// Displaying the Key value Pairs
for (Map.Entry < Character, Integer > entry: list) {
System.out.println(entry.getKey() + " \t " + entry.getValue());
}
}
private static void checkMap(char c) {
// Checking whether the word is available in the HashMap
if (m.containsKey(c)) {
m.put(c, m.get(c) + 1);
} else {
// If not available Adding the word to the HashMap
m.put(c, 1);
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started