I have an array of bytes ( primitive ), they can have random values. I am trying to count them in an array in the most efficient / fastest way. I am currently using:
HashMap<Byte, Integer> dataCount = new HashMap<>(); for (byte b : data) dataCount.put(b, dataCount.getOrDefault(b, 0) + 1);
This one-line line takes ~ 500 ms to process byte [] with a length of 24883200 . Using a regular loop for a loop takes at least 600 ms.
I was thinking of creating a set (since it contains only one of each element) and then adding it to the HashMap using Collections.frequency (), but the methods for constructing a set from primitives require several other calls, so I assume it is not so fast .
What would be the fastest way to count the events of each element?
I am using Java 8 and I would prefer to avoid using Apache Commons if possible.
source share