Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions