25
less code (words frequency)
A blog that solves a programming puzzle (words frequency kata) in three ways.
The goal is first to write a correct program, then at each solution
to reduce the total lines of the program.
The goal is first to write a correct program, then at each solution
to reduce the total lines of the program.
The problem has as an input a string with characters and as an output a map
that the key is a character and a value how many times this character appeared.
that the key is a character and a value how many times this character appeared.
input: "aaabb"
output: {a: 3, b: 2} // in java map the keys are the a, b and the corresponding values 3, 2
output: {a: 3, b: 2} // in java map the keys are the a, b and the corresponding values 3, 2
Map<Character, Integer> computeFrequencies(String input)
public static Map<Character, Integer> computeFrequenciesV1(String input) {
Map<Character, Integer> result = new HashMap<>();
for (int index = 0 ; index < input.length(); index++) {
char c = input.charAt(index);
if (result.containsKey(c)) {
Integer oldValue = result.get(c);
result.put(c, ++oldValue);
} else {
result.put(c, 1);
}
}
return result;
}
solution explanation
solution total lines: 11
public static Map<Character, Integer> computeFrequenciesV2(String input) {
Map<Character, Integer> result = new HashMap<>();
for (int index = 0 ; index < input.length(); index++) {
char c = input.charAt(index);
result.compute(c, (key, value) -> value == null ? value = 1 : ++value);
}
return result;
}
solution explanation
solution total lines: 6 from 11, not bad and still readable I think
public static Map<Character, Long> computeFrequenciesV3(String input) {
return input.chars()
.mapToObj(c -> (char) c)
.collect(groupingBy(c -> c, Collectors.counting()));
}
solution explanation
solution total lines: 3, we have a winner!
groupingBy explanation:
for example (in our case): "aaabb"
the keys will be: a, b two groups in total
the keys will be: a, b two groups in total
for example (in our case): "aaabb"
the group with "a" we count three elements,
while in the "b" group we count two element.
the group with "a" we count three elements,
while in the "b" group we count two element.
If you haven't specified an action you will had a map with two keys and values:
key: 'a'
value: ['a', 'a', 'a']
value: ['a', 'a', 'a']
key: "b"
value: ['a', 'a']
value: ['a', 'a']
the action operates in the lists (the reduction step).
25