how to compare two set values
Hi guys,
I need to itterate through 2 sorted sets and compare the values in the set. These sets are of type String and are called listOfNames1 and listOfNames2. If they are not the same i need these values to be added to another set called different.
The code I have is below. This works as I expect it to when i change if (names1 != names2) to if (names1 == names2) but when im trying to get it to add the names that are not the same it just adds all the names in listOfNames1 to the sortedSet different.
Code :
public void notTheSame()
{
SortedSet<String>different = new TreeSet<String>();
for(String names1 : listOfNames1)
{
for(String names2 : listOfNames2)
{
if (names1 != names2)
{
different.add(names1);
}
}return null;
}
Hope someone can help. thankyou in advance for anyone that takes the time to try.
Re: how to compare two set values
There is an easier way to find similarities and differences between sets...look at The Set Interface (The Java™ Tutorials > Collections > Interfaces) and scroll down to the Bulk Operations where there are code listings for how to go about doing this. For example, to find the difference:
Code :
Set<String> difference = new HashSet<String>(listOfNames1);
difference.removeAll(listOfNames2);