Using TreeMap to auto-sort. This is basically the way I did the earlier tasks where you count letters and spaces. I waited until the print statement to cast into a character in case that messed up the TreeMap sorting since I don't know how that works. Why is it that every task here now makes me want to quit learning Java?
The output looks right, except that I'm counting new lines and carriage returns, as well as spaces, and I don't know if that stuff is making it fail validation, or what's going on.
package com.codegym.task.task18.task1821;
/*
Symbol frequency
*/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Solution {
public static void main(String[] args) throws IOException {
TreeMap<Integer, Integer> symbols = new TreeMap<>();
if (args.length > 0) {
File file = new File(args [0]);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis, 200);
int i;
while ((i = bis.read()) != -1) {
if (!symbols.containsKey(i)) {
symbols.put(i, 0);
}
else {
int temp = symbols.get(i);
symbols.put(i, temp + 1);
}
}
bis.close();
}
Set<Map.Entry<Integer, Integer>> set = symbols.entrySet();
for (Map.Entry<Integer, Integer> me : set) {
int i = me.getKey();
System.out.print((char) i + " ");
System.out.println(me.getValue());
}
}
}