Creating two constructs for University second semester computer science to count words in a text. One implementation uses an Array with Word-Objects which save the word as string and its frequency as int. The other uses as HashMap with the Word as key and the frequency as value. Now their is a function "totalWords" that should return the sum of all frequency.
In the HashMap variant:
return _map.values().stream().reduce(0, (a, b) -> a + b);
In the array variant:
return Arrays.stream(_words)
.map((word) -> word != null ? word.count() : 0)
.reduce(0, (a, b) -> a + b);
My problem is: in a JUnit test with a very short test text the Array variant does need approximately 0.001s and the map variant needs 0.040s and I do not understand why the map does need so much more time. Has anybody an explanation and maybe a better solution?
LinkedHashMaptends to be noticably faster than for a plainHashMap. Not as fast as for an array, though...