Java - Write code to return difference set operation

Requirements

Write code to return difference set operation

Demo

//package com.book2s;
import java.util.*;

public class Main {
    public static void main(String[] argv) {
        String[] list1 = new String[] { "1", "abc", "level", null,
                "book2s.com", "asdf 123" };
        String[] list2 = new String[] { "1", "abc", "level", null,
                "book2s.com", "asdf 123" };
        System.out.println(java.util.Arrays.toString(difference(list1,
                list2)));/*from   w w  w.  j a  v a  2  s.com*/
    }

    /**
     * The difference set operation
     *
     * @param list1
     * @param list2
     * @return the set of all items not in both lists
     */
    public static String[] difference(final String[] list1,
            final String[] list2) {
        HashSet<String> set = new HashSet<String>();
        HashSet<String> set1 = new HashSet<String>(Arrays.asList(list1));
        HashSet<String> set2 = new HashSet<String>(Arrays.asList(list2));
        for (final String s : list1) {
            if (!set2.contains(s)) {
                set.add(s);
            }
        }
        for (final String s : list2) {
            if (!set1.contains(s)) {
                set.add(s);
            }
        }
        return set.toArray(new String[set.size()]);
    }

    /**
     * Returns true if the value is in the list.
     * @param list
     * @param value
     * @return
     */
    public static boolean contains(final String[] list, final String value) {
        HashSet<String> set = new HashSet<String>(Arrays.asList(list));
        return set.contains(value);
    }
}

Related Exercise