# Count duplicates in a TreeSet Collection

Quiddo Quitch
Ranch Hand
Posts: 38
i was wondering, is there anyway to know how many duplicates were detected in a TreeSet Collection ?

for example in the following code there are 3 duplicates ... is there anyway to get that value ?

thanks !!

Sheriff
Posts: 14691
16
Methods usually return some useful information. Did you check what the add method of java.util.TreeSet returns ?

Quiddo Quitch
Ranch Hand
Posts: 38
yes i checked the returns methods, i have the method "size()" to determine the number of elements in the collection, but that not give me the number of duplicates

Quiddo Quitch
Ranch Hand
Posts: 38
i figure it out, you can close this thread ...

the solution is to count all elements and then rest it to size() method ... finally you get the duplicates number

K. Tsang
Bartender
Posts: 3443
13
A set contains no duplicates. So the size() method won't help. In fact what does add() returns? boolean right? Now does add return false if you add integer 1 the 2nd time? if so you can have a variable to keep track of this and will return 3 in your code.

Mike Simmons
Ranch Hand
Posts: 3076
14
What if you count how many times add() was called? Then if, for example, add() was called 35 times, but the final size() is 28, there must have been 7 duplicates.

Or, what if you counted how many times add() returned true?

Quiddo Quitch
Ranch Hand
Posts: 38
K. Tsang wrote:A set contains no duplicates. So the size() method won't help. In fact what does add() returns? boolean right? Now does add return false if you add integer 1 the 2nd time? if so you can have a variable to keep track of this and will return 3 in your code.

i used a List to count the total results and a Set to have no duplicates ... then i got the size() of List minus the size() of Set ... this is probably not the smartest way, but it worked like a charm xD

Sheriff
Posts: 14691
16
this is probably not the smartest way

Surely not You misunderstood my hint. K. Tsang described what I wanted to tell you : use add()'s return value to determine if an element was added or not.

Rob Spoor
Sheriff
Posts: 20527
54
Perhaps you should use a org.apache.commons.collections.Bag