I wonder if there are any java collection counting occurences in a set.
Since it just stores the references once and gets the number of times it was added it saves space but allows you to know the number of times it was added. It also saves space in case you need to know if there are available items or not.
For example:
Set<Object> counterSet = new Set<Object>();
counterSet.add("Hello");
counterSet.add("world");
counterSet.add("Hello");
counterSet.numberOfInstances("Hello"); //returns 2
counterSet.numberOfInstances("world"); //returns 1
I've been looking for it but I don't find a collection like this, could you tell me the best way to do it?
A Set doesn't allow duplicates. Instead look into using a Map<String, Integer> or a List<String> and then use Collections.frequency to get the count.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With