-1

I need to get the size of an intersected set, and I then need to use the size in a formula.

Set<String> a;
Set<String> b;
a.retainAll(b).size();
// error: cannot invoke size() on primitive type boolean//

I've tried to do this in several different ways, but my code only got more and more complicated. Can anyone set me on the right path?

Thanks.

Mtribe
  • 1
  • 1
  • Welcome to SO! I hope you'll find the site useful. In my experience, learning to use the site also helped me to grow personally as a developer. This is a great start to asking a good question. You have an idea about what you want to achieve and it makes sense intuitively, however it is missing an example of what you've tried together with the output you observed and the desired output. Please consider adding these such that other users can test your code and provide you with code in return that's useful for you. – Bobby Nov 05 '16 at 10:53

1 Answers1

2

According to documentation retainAll method returns a boolean -- whether set was changed. You may ignore this value. The main effect of this method is a modification of set a, so it contains an intersection. Therefore, the solution is

a.retainAll(b);
int result = a.size();

Notice, that contents of set a is changed by this code. If you need to preserve it:

Set<String> intersection = new HashSet<String>(a);
inersection.retainAll(b);
int result = intersection.size();
kgeorgiy
  • 1,477
  • 7
  • 9