Tuesday, January 31, 2012

Java Set Operations

As you know, for a while I’ve been playing with Solr. Basically implementing federated search framework to aggregate different ERP, CRM, PLM space data sources.
This post is not about federated search but I keep using bunch of set operations to compare the search results, comparing the unique doc id etc.

public class SetOperations {
public static Set union(Set setA, Set setB) {
Set tmp = new TreeSet(setA);
tmp.addAll(setB);
return tmp;
}

public static Set intersection(Set setA, Set setB) {
Set tmp = new TreeSet();
for (T x : setA)
if (setB.contains(x))
tmp.add(x);
return tmp;
}

public static Set difference(Set setA, Set setB) {
Set tmp = new TreeSet(setA);
tmp.removeAll(setB);
return tmp;
}

public static void main(String[] args) {

SortedSet s1= new TreeSet();
s1.add("one");
s1.add("two");

SortedSet s2= new TreeSet();
s2.add("two");
s2.add("three");
s2.add("four");

SortedSet result = (SortedSet) union(s1,s2);

Iterator it = result.iterator();
System.out.print("union result -->");
while (it.hasNext()) {
String value = it.next();
System.out.print(value+", ");
}
System.out.println("\n");

result = (SortedSet) intersection(s1,s2);

it = result.iterator();
System.out.print("intersection result-->");
while (it.hasNext()) {
String value = it.next();
System.out.print(value+ ", ");
}
System.out.println("\n");

result = (SortedSet) difference(s1,s2);

it = result.iterator();
System.out.print("difference result-->");
while (it.hasNext()) {
String value = it.next();
System.out.print(value+", ");
}
System.out.println("\n");

/*
SortedSet i1= new TreeSet();
i1.add(new Integer("1"));

SortedSet i2= new TreeSet();
i2.add(new Integer("2"));

SortedSet iresult = (SortedSet) union(i1,i2);

Iterator iit = iresult.iterator();
System.out.println("Integer union result");
while (iit.hasNext()) {
Integer value = iit.next();
System.out.println(value+",");
}
*/
}

}

No comments: