Java List Difference difference(final String[] list1, final String[] list2)

Here you can find the source of difference(final String[] list1, final String[] list2)

Description

The difference set operation

License

Apache License

Parameter

Parameter Description
list1 list1
list2 list2

Return

the set of all items not in both lists

Declaration

public static String[] difference(final String[] list1, final String[] list2) 

Method Source Code


//package com.java2s;
/*//from w  ww . jav  a  2  s  .  co m
 * Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.*;

public class Main {
    /**
     * The difference set operation
     *
     * @param list1 list1
     * @param list2 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()]);
    }

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

Related

  1. diff(List ls, List ls2)
  2. diff(List doublesA, List doublesB)
  3. diffAsSet(Collection list1, Collection list2)
  4. difference(final List minuend, final List subtrahend)
  5. difference(final List list1, final List list2)
  6. difference(List firstList, List secondList)
  7. difference(List lst1, List lst2)
  8. difference(List set1, List set2)
  9. differenceOfList(List a, List b)