I made this quick code for a class and I got everything to work fine as far as reading the text file and printing it out, but I can't figure out how to get it to print out in ascending order. The goal is to read a file and print out the number of times that word appears and sort it by the number of times it appears.
public class Analyser {
public static void main(String[] args) throws IOException {
File file = new File("src/txt.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
Map<String, Long> counts = new HashMap<>();
while ((line = br.readLine()) != null) {
String[] words = line.split("[\\s.;,?:!()\"]+");
for (String word : words) {
word = word.trim();
if (word.length() > 0) {
if (counts.containsKey(word)) {
counts.put(word, counts.get(word) + 1);
} else {
counts.put(word, 1L);
}
}
}
}
for (Map.Entry<String, Long> entry : counts.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
br.close();
}
}