Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Sets and creating a new set containing a common number

1. ## Sets and creating a new set containing a common number

I have 4 Sets that contains numbers.

I need to find the common numbers from all the sets and store this in another set

e.g.

Set1 = 1,5,6,9,10,12,15
Set2 = 3,5,6,9,60,80
Set3 = 1,5,6,8,9
Set4 = 1,5,6,90,500,1000

So in essence i need to find the numbers that are contained it every set, in this case its 5 and 6.

I then need to store these in another set.

I have no problems create a new set etc but struggling with how to loop through all the sets and pick the common number

Any help would be appriciated, its more of a concept request than a code request, e.g. do i use the contains() method

Thanks

2. ## Re: Sets and creating a new set containing a common number

A simple O(nlogn) (actually, depends on which sorting algorithm you use, but this is using quicksort) method is to put everything you have there into one sorted array. Then work your way through the list, and if find any duplicate values (they will be right next to each other), put that into your set.

thanks :-)