Returns common elements in two lists if any of input lists are null then the other one will be returned. - Java java.util

Java examples for java.util:List Value

Description

Returns common elements in two lists if any of input lists are null then the other one will be returned.

Demo Code


//package com.java2s;
import java.io.IOException;

import java.util.List;

public class Main {
    /**//from  ww w.j  a  v  a 2s  .  c o  m
     * 
     * Returns common elements in two lists if any of input lists are null
     * then the other one will be returned. If both lists are null then exception i thrown.
     * 
     * @param <T>
     *            list elements class.
     * @param list1
     *            first list.
     * @param list2
     *            second list.
     * @return common elements that are not null.
     * @throws IOException
     *             if both lists are null.
     */
    public static <T> List<T> getCommonElements(List<T> list1, List<T> list2)
            throws IOException {
        if (list1 == null) {
            if (list2 == null) {
                throw new IOException("Both lists are null!");
            } else {
                return list2;
            }
        } else {
            if (list2 != null) {
                list1.retainAll(list2);
            }
            return list1;
        }
    }
}

Related Tutorials