Let me know if there is a better way to do this.
I was thinking of using some kind of a sorted map instead of iterating through the entrySet and storing the highest values, but I did not find relevant information regarding this.
package com.codegym.task.task18.task1823;
import java.io.*;
import java.security.KeyStore;
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 IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//read filenames from the console until the word "exit" is entered
//pass the filename to the readthread thread
//the thread should find the byte (so the element, not how many times it occurs)
//that occurs most frequently in the file and add it to
//the resultMap where the String parameter is the fileName and the Integer parameter is
//the relevant byte.
while (true){
String fileName = br.readLine();
if (fileName.equals("exit")) {
br.close();
break;
}
ReadThread readThread = new ReadThread(fileName);
readThread.start();
}
}
public static class ReadThread extends Thread {
String fileName;
public ReadThread(String fileName) throws FileNotFoundException {
// Implement constructor body
this.fileName = fileName;
}
public void run(){
// Implement file reading here
//I have created a map in which I will add all of the elements from the file
//and the number of times they are found
HashMap<Integer, Integer> sortedMap = new HashMap<>();
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
//here I am reading the bytes from the file
while (fileInputStream.available()>0){
int byteRead = fileInputStream.read();
//the condition below checks if the file is present and increments value
//or adds the key to the map and value 1 because it is the 1st time it shows up
if (sortedMap.containsKey(byteRead)){
sortedMap.replace(byteRead, sortedMap.get(byteRead) + 1);
} else sortedMap.put(byteRead, 1);
}
//here I declare a value and key which will store value and key when I iterate
//through the map
int value = Integer.MIN_VALUE;
int key = 0;
//declaring the entry set -a clone- of the sortedMap
Set<Map.Entry<Integer,Integer>> entries = sortedMap.entrySet();
//iterating through the clone
for(Map.Entry<Integer,Integer> entry:entries) {
if(entry.getValue() >= value) {
value = entry.getValue();
key = entry.getKey();
}
}
resultMap.put(fileName, key);
fileInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}