Java List Intersect intersectList(List list1, List list2)

Here you can find the source of intersectList(List list1, List list2)

Description

Intersect list.

License

Apache License

Parameter

Parameter Description
T the generic type
list1 the list1
list2 the list2

Return

the list

Declaration

public static <T> List<T> intersectList(List<T> list1, List<T> list2) 

Method Source Code


//package com.java2s;
/*//from w ww  . ja va  2 s  .com
Copyright 2014 Array-Utilities
    
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.ArrayList;

import java.util.Collection;

import java.util.List;

public class Main {
    /**
     * Intersect list.
     *
     * @param <T> the generic type
     * @param list1            the list1
     * @param list2            the list2
     * @return the list
     */
    public static <T> List<T> intersectList(List<T> list1, List<T> list2) {

        if (isEmpty(list1) && isEmpty(list2)) {
            return new ArrayList<T>();
        }
        // list1 empty & list2 has values
        if (isEmpty(list1) && !isEmpty(list2)) {
            return new ArrayList<T>();
        }

        // list1 has values & list2 is empty
        if (!isEmpty(list1) && isEmpty(list2)) {
            return new ArrayList<T>();
        }

        if (list1.equals(list2)) {
            return list1;
        }

        List<T> list3 = new ArrayList<T>();
        for (T object : list1) {
            if (list2.contains(object)) {
                if (!list3.contains(object)) {
                    list3.add(object);
                }
            }
        }
        return list3;
    }

    /**
     * Checks if is empty.
     *
     * @param <E>
     *            the element type
     * @param collection
     *            the collection
     * @return true, if is empty
     */
    public static <E> boolean isEmpty(Collection<? super E> collection) {

        if ((collection.size() == 0) || (collection == null))
            return true;
        return false;
    }
}

Related

  1. intersection(List arrayOne, List arrayTwo)
  2. intersection(List listOne, List listTwo)
  3. intersection(List set1, List set2)
  4. intersection_type(List list1, List list2)
  5. intersectionInplace(List> sets)
  6. intersectSortedAscending(List l1, List l2)
  7. isListIntersect(List list1, List list2)
  8. removeIntersection(List intervals, List intervalsToRemove)