package commonCharacter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class MostCommonCharacters {
public static void main(String[] args) {
String characters = String.valueOf(fileReader("countchar.txt"));
getTwoMostCommonCharacters(characters);
}
private static void getTwoMostCommonCharacters(String fileName){
HashMap<Character, Integer> charCountMap = new HashMap<>();
char[] charArray = fileName.replaceAll("\\s+", "").toCharArray();
for (char temp : charArray) {
if (charCountMap.containsKey(temp)) {
charCountMap.put(temp, charCountMap.get(temp) + 1);
} else {
charCountMap.put(temp, 1);
}
}
Collection<Integer> values = charCountMap.values();
ArrayList<Integer> listOfValues = new ArrayList<>(values);
Collections.sort(listOfValues);
List<Integer> highValue = List.of(listOfValues.get(listOfValues.size()-1));
List<Integer> secondHighValue = List.of(listOfValues.get(listOfValues.size()-2));
String formattedString1 = highValue.toString()
.replace(",", "")
.replace("[", "")
.replace("]", "")
.trim();
String formattedString2 = secondHighValue.toString()
.replace(",", "")
.replace("[", "")
.replace("]", "")
.trim();
System.out.println(getKeyByValue(charCountMap,listOfValues.get(listOfValues.size()-1)) + ": " + formattedString1);
System.out.println(getKeyByValue(charCountMap,listOfValues.get(listOfValues.size()-2)) + ": " + formattedString2);
}
public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Map.Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}
private static List<String> fileReader(String fileName) {
Path filePath = Paths.get(fileName);
try {
List<String>fileline= Files.readAllLines(filePath);
return fileline;
} catch (IOException e) {
System.out.println("File does not exist!");
return null;
}
}
}