Java List Value Add All addAllUnique(List l1, T element)

Here you can find the source of addAllUnique(List l1, T element)

Description

Add the element to the list, if it is not already there.

License

Open Source License

Parameter

Parameter Description
T a parameter
l1 a parameter
element a parameter

Declaration

public static <T> List<T> addAllUnique(List<T> l1, T element) 

Method Source Code

//package com.java2s;
/*//from   ww  w  .j a  v a  2 s  .co m
 *  Copyright (c) Ludger Solbach. All rights reserved.
 *  The use and distribution terms for this software are covered by the
 *  Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
 *  which can be found in the file license.txt at the root of this distribution.
 *  By using this software in any fashion, you are agreeing to be bound by
 *  the terms of this license.
 *  You must not remove this notice, or any other, from this software.
 */

import java.util.List;

public class Main {
    /**
     * Adds the content of the second list to the first list, but checks for each element if the element is not already there.
     * To be used as a Set replacement, if the order of inserts is relevant.
     * @param <T>
     * @param l1
     * @param l2
     * @return
     */
    public static <T> List<T> addAllUnique(List<T> l1, List<T> l2) {
        for (T element : l2) {
            if (!l1.contains(element)) {
                l1.add(element);
            }
        }
        return l1;
    }

    /**
     * Add the element to the list, if it is not already there.
     * To be used as a Set replacement, if the order of inserts is relevant.
     * @param <T>
     * @param l1
     * @param element
     * @return
     */
    public static <T> List<T> addAllUnique(List<T> l1, T element) {
        if (!l1.contains(element)) {
            l1.add(element);
        }
        return l1;
    }
}

Related

  1. addAllTo(List procArgs, String[] args)
  2. addAllTo(List list, T... args)
  3. addAllToANewList(Collection... collections)
  4. addAllToList(List dest, Collection src)
  5. addAllUnique(List aList, List theObjects)
  6. addAllUniqueId(List aList, List theObjects)
  7. addAllUniqueToList(List objects, List objectsToAdd)
  8. addAllWords(String text, List result)
  9. addArrayToList(List list, String as[])