I tried an approach without using HashMaps. Can anyone tell me if the code is doing what I think it's doing?
The idea was to find the frequency of most frequent and then loop through the byte array again. In the new loop I'm adding to a new ArrayList <byte> all the items with max frequency.
Thanks!
package com.codegym.task.task18.task1803;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*
Most frequent bytes
Requirements:
1. The program should read a file name from the console.
2. Use a FileInputStream to read from the file.
3. All of the most frequently repeated bytes from the file should be displayed, separated by spaces.
4. The screen output should be displayed in one line.
5. The stream used to read the file must be closed.
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fileName = reader.readLine();
File file = new File(fileName);
FileInputStream fis = null;
List <Byte> result = new ArrayList<>();
try {
fis = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
fis.read(fileContent);
Arrays.sort(fileContent);
int max = 1;
byte temp = fileContent[0];
int count = 1;
for (int i = 1; i<fileContent.length; i++) {
if (fileContent[i] == fileContent[i-1]) {
count++;
} else {
if (count > max) {
max = count;
temp = fileContent[i-1];
}
count = 1;
}
}
int max1 = 1;
byte temp2 = fileContent[0];
for (int i = 1; i<fileContent.length; i++) {
if (fileContent[i] == fileContent[i-1]) {
count++;
if (count == max) {
result.add(temp2);
}
} else {
if (count > max1) {
max1 = count;
temp2 = fileContent[i-1];
}
count = 1;
}
}
for (byte b: result){
System.out.print(b+" ");
}
} catch (IOException e) {
System.out.println("exception reading file");
} finally {
if (fis != null) {
fis.close();
}
}
}
}