Question: How do you sort a hashmap in java? My code reads any text document and counts the number of times each word is used and

How do you sort a hashmap in java?

My code reads any text document and counts the number of times each word is used and puts it into a hashmap. Now I would like to sort the words alphabetically. I have tried to convert the words to a list and then use Collections.sort() but that didn't seem to work. import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.HashMap; import java.util.Scanner;

public class Odyssey {

public static void main(String[] args) throws FileNotFoundException {

HashMap wordCount = new HashMap (); Scanner sc = new Scanner(System.in); System.out.println("Enter the file location:");//ask user File file = new File(sc.nextLine());//set user input to file try (Scanner br = new Scanner(new FileReader(file))) {//set scanner to read file

String line = br.nextLine().toLowerCase(); //read lines of the file

while (br.hasNext()) { //replace character line = line.replace(",", " "); line = line.replace("_", " "); line = line.replace(".", " "); line = line.replace(":", " "); line = line.replace(")", " "); line = line.replace("]", " "); line = line.replace("[", " "); line = line.replace("(", " "); line = line.replace("#", " "); line = line.replace("!", " "); line = line.replace("?", " "); line = line.replace(";", " "); line = line.replace("", " "); line = line.replace("", " "); line = line.replace("", " "); line = line.replace("", " "); line = line.replace("\"", " "); line = line.replace("-", " ");

String[] words = line.split(" ");//create array of words

for (int i = 0; i < words.length; i++) {//add words

if (wordCount.get(words[i]) == null) {

wordCount.put(words[i], 1);

} else {

int value = Integer.valueOf(String.valueOf(wordCount.get(words[i])));

value++;

wordCount.put(words[i], value);

}

}

line = br.nextLine().toLowerCase();//read next line

}

} catch (FileNotFoundException e) {//if file is not found

System.out.println("File not Found");

}

for (Object key : wordCount.keySet()) {//traverse through hashmap

System.out.println(wordCount.get(key) + " " + key);//print count and words

} sc.close();//close scanner } }

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!