Java examples for java.util:Collection Operation
Return the junction between two Collection
//package com.book2s; import java.util.*; public class Main { public static void main(String[] argv) { Collection a = java.util.Arrays.asList("asdf", "book2s.com"); Collection b = java.util.Arrays.asList("asdf", "book2s.com"); System.out.println(junction(a, b)); }// w w w .j a v a 2 s. c o m /** * Answer the junction between a and b. Answer is of the same type as a. * * @param a * @param b * @return */ public static Collection junction(Collection a, Collection b) { Collection answer = createCollection(a); for (Iterator i = a.iterator(); i.hasNext();) { Object oa = i.next(); for (Iterator k = b.iterator(); k.hasNext();) { Object ob = k.next(); if (oa.equals(ob)) { answer.add(oa); } } } return answer; } /** * Create and answer a collection that is the same type, or the closest * equivalent of col. * * @param col * @return */ public static Collection createCollection(Collection col) { Collection answer; try { answer = (Collection) col.getClass().newInstance(); } catch (Exception e) { if (col instanceof List) { answer = new ArrayList(); } else if (col instanceof SortedSet) { answer = new TreeSet(); } else if (col instanceof Set) { answer = new HashSet(); } else { answer = new ArrayList(); // should this throw an exception? } } return answer; } }