I am trying to write a program to order a list of strings by most least frequent characters within the list. For example, if the list was [apple, orange, banana] the letter frequency within the list would be a - 5, n - 3, p - 2, e - 2, l- 1, o - 1, r - 1, g - 1, b - 1. Since orange contains the most least frequent letters, the program would return orange, then apple then banana.
So far I've written the code that orders all the letters in the list by frequency. But I need to apply that to find which string contains the most least frequent letters.
Here is my code:
Map<Character, Integer> elemCount = new LinkedHashMap<>();
for (String word : words)
{
for (int i = 0; i < word.length(); i++)
{
if (elemCount.containsKey(word.charAt(i)))
{
elemCount.put(word.charAt(i), elemCount.get(word.charAt(i)) + 1);
}
else
{
elemCount.put(word.charAt(i), 1);
}
}
}
ArrayList<Character> sortedElems = new ArrayList<>();
elemCount.entrySet().stream().sorted(Collections.reverseOrder
(Map.Entry.comparingByValue())).forEach(entry ->
{
for (int i = 1; i <= entry.getValue(); i++)
{
sortedElems.add(entry.getKey());
}
}
);
System.out.println(sortedElems);