Convert a varargs list of items into a Set while preserving order. - Java java.util

Java examples for java.util:List Convert

Description

Convert a varargs list of items into a Set while preserving order.

Demo Code


//package com.java2s;

import java.util.LinkedHashSet;

import java.util.Set;

public class Main {
    /**//from ww w. ja v  a  2 s.  co m
     * Convert a varargs list of items into a Set while preserving order. An empty set is returned if items is null.
     * 
     * @param <T>
     *            Any type of object
     * @param items
     *            A variable length list of items of type T
     * @return Returns a new LinkedHashSet<T> or an empty set
     */
    public static final <T> Set<T> newInOrderSet(T... items) {
        return addToSet(new LinkedHashSet<T>(items != null ? items.length
                : 0), items);
    }


    public static final <T, U extends T> Set<T> addToSet(Set<T> set,
            U... items) {
        if (set != null && items != null) {
            for (int i = 0; i < items.length; i++) {
                set.add(items[i]);
            }
        }

        return set;
    }
}

Related Tutorials