Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set counting items

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?

like image 403
David Marciel Avatar asked Dec 22 '25 09:12

David Marciel


1 Answers

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.

like image 73
Ousmane D. Avatar answered Dec 23 '25 23:12

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!