I had it initially where it was returning the right answer, but I didn't write my code to utilize threads (I didn't have a start and run method). I changed some things around while I thought I was keeping my logic the same, and now not only did I fail to create and start a ReadThread, now I'm not even getting the right answer.
I feel like my code starts off nice and neat and simple, but as I struggle to reach validation I start hobbling things on to pass requirements and everything just starts looking like a mess. Basically I was using a comparator to sort the values in my HashMap, and then, because the last value was the largest, I just cycled through replacing the result variable every time, as the last getKey would be the Key associated with the largest frequency of occurring byte. Maybe that was stupid, but it worked initially, and now it doesn't.
And apparently I'm not even starting a thread?
package com.codegym.task.task18.task1823;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.*;
/*
Threads and bytes
*/
public class Solution {
public static Map<String, Integer> resultMap = new HashMap<String, Integer>();
public static void main(String[] args) throws Exception{
String file = null;
Scanner sc = new Scanner(System.in);
while (true) {
file = sc.nextLine();
if (file == "exit")
break;
else {
ReadThread t = new ReadThread(file);
t.start();
resultMap.put(file, t.frequent);
}
}
}
public static class ReadThread extends Thread {
FileInputStream fis;
BufferedInputStream bis;
Integer frequent;
public ReadThread(String fileName) throws Exception{
this.fis = new FileInputStream(fileName);
this.bis = new BufferedInputStream(fis);
}
public void run() {
try {
this.frequent = mostFrequent(this);
}
catch (Exception e) {}
}
public static Integer mostFrequent (ReadThread thread) throws Exception {
HashMap <Integer, Integer> count = new HashMap<>();
int i;
while ((i = thread.bis.read()) != -1) {
count.put(i, count.getOrDefault(i, 0) + 1);
}
thread.bis.close();
List<Map.Entry<Integer, Integer> > list = new LinkedList<Map.Entry<Integer, Integer>>(count.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Integer result = 0;
for (Map.Entry<Integer, Integer> aa : list) {
result = aa.getKey();
}
return result;
}
}
}