Question: 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

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!