Java 8
Approach 1 - Gets the occurrence of a single character
String sentence = "Aaron ate apples upon a rock";
long counted = IntStream.range(0, sentence.length())
.filter(i->sentence.charAt(i) == 'a')
.count();
System.out.println("First approach: " + counted);
Approach 2 - Allows the character to be specified
String sentence = "Aaron ate apples upon a rock";
BiFunction<String, Character, Long> counter = (s,c) -> {
return IntStream.range(0, s.length())
.filter(i->s.charAt(i) == c)
.count();
};
System.out.println("Second approach (with 'a'): " + counter.apply(sentence, 'a'));
System.out.println("Second approach (with 'o'): " + counter.apply(sentence, 'o'));
Approach 3 - Counts occurrences of all characters
String sentence = "Aaron ate apples upon a rock";
Map<Character, Long> counts = IntStream.range(0, sentence.length())
.mapToObj(i->sentence.charAt(i))
.collect(Collectors.groupingBy(o->o, Collectors.counting()));
System.out.println("Third approach for every character... ");
counts.keySet().stream()
.forEach(key -> System.out.println("'" + key + "'->" + counts.get(key)));