Given two collections of elements of type , return a collection with the items which only appear in both lists - Java java.util

Java examples for java.util:Collection Element

Description

Given two collections of elements of type , return a collection with the items which only appear in both lists

Demo Code


//package com.java2s;

import java.util.Collection;
import java.util.Collections;

import java.util.HashSet;

import java.util.Map;
import java.util.Set;

public class Main {
    public static void main(String[] argv) {
        Collection collection1 = java.util.Arrays.asList("asdf",
                "java2s.com");
        Collection collection2 = java.util.Arrays.asList("asdf",
                "java2s.com");
        System.out.println(intersect(collection1, collection2));
    }/*w  ww  .j av a  2  s.c o m*/

    /**
     * Given two collections of elements of type <T>, return a collection with the items which only appear in both lists
     * 
     * @param <T>
     *            Type
     * @param collection1
     *            Collection #1
     * @param collection2
     *            Collection #2
     * @return Collection with items common to both lists
     */
    public static <T> Collection<T> intersect(Collection<T> collection1,
            Collection<T> collection2) {
        if (isEmpty(collection1) || isEmpty(collection2)) {
            return Collections.emptyList();
        }

        Set<T> intersection = new HashSet<T>(collection1);

        intersection.retainAll(collection2);

        return intersection;
    }

    /**
     * This is a convenience method that returns true if the specified collection is null or empty
     * 
     * @param <T>
     *            Any type of object
     * @param collection
     * @return
     */
    public static <T> boolean isEmpty(Collection<T> collection) {
        return collection == null || collection.isEmpty();
    }

    /**
     * This is a convenience method that returns true if the specified map is null or empty
     * 
     * @param <T>
     *            any type of key
     * @param <U>
     *            any type of value
     * @param map
     * @return
     */
    public static <T, U> boolean isEmpty(Map<T, U> map) {
        return map == null || map.isEmpty();
    }
}

Related Tutorials