Find Union of Two Collections in Java
I explained in this post how to find the intersection of two collections in Java. This post will explain how to find the union of two collections. A union means finding all unique values from the two lists combined.
import java.util.*; public static Collection Union(Collection coll1, Collection coll2) { Set union = new HashSet(coll1); union.addAll(new HashSet(coll2)); return new ArrayList(union); } Set set1 = new HashSet(); set1.add("abc"); set1.add("def"); Set set2 = new HashSet(); set2.add("def"); set2.add("ghi"); for (Object item : Intersect(set1, set2)) System.out.println(item);
This would output:
abc
def
ghi
You have a nifty blog here. I always find blogs like this really interesting because I come across solutions to things I had given up on before or problems I wouldn’t have foreseen. You’ve got yourself at least one regular reader.