Map
fits the case to get characters based on number of occurrences. Map
is just structure that store data in the pairs key-value. See here for details.
So to get characters and it's number of occurrences without java8 you can do like:
public Map<Character, Long> countChar(String string) {
Map<Character, Long> result = new LinkedHashMap<>();
char[] chars = string.toCharArray();
for (char c : chars) {
if (result.get(c) != null) {
result.put(c, result.get(c) + 1);
} else {
result.put(c, 1L);
}
}
return result;
}
Next you want to sort values by number of occurrences. In this case you can sort the result map by value. See Sort a Map<Key, Value> by values to find the solution you more familiar with. To do this without stream, but using java8:
List<Map.Entry<Character, Long>> list = new ArrayList<>(result.entrySet());
list.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
And now you can print each char like:
StringBuilder output = new StringBuilder();
for (Map.Entry<Character, Long> entry : list) {
output.append(entry.getKey());
}
System.out.println(output);