as Immutable Set - Android java.util

Android examples for java.util:Set

Description

as Immutable Set

Demo Code

/*****************************************************************************************
 * *** BEGIN LICENSE BLOCK *****/*  w  w w .  java2s .  c o m*/
 *
 * Version: MPL 2.0
 *
 * echocat Locela - API for Java, Copyright (c) 2014-2016 echocat
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * *** END LICENSE BLOCK *****
 ****************************************************************************************/
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
import static java.util.Collections.*;
import static org.echocat.locela.api.java.utils.ResourceUtils.closeQuietlyIfAutoCloseable;

public class Main{
    @Nonnull
    public static <T> Set<T> asImmutableSet(@Nullable Iterable<T> in) {
        return unmodifiableSet(asSet(in));
    }
    @Nonnull
    public static <T> Set<T> asSet(@Nullable Iterable<T> in) {
        final Set<T> result;
        if (in instanceof Set) {
            result = (Set<T>) in;
        } else if (in instanceof Collection) {
            result = new LinkedHashSet<>((Collection<T>) in);
        } else {
            result = addAll(new LinkedHashSet<T>(), in);
        }
        return result;
    }
    @Nonnull
    public static <T, C extends Collection<T>> C addAll(@Nonnull C to,
            @Nullable T... elements) {
        if (elements != null) {
            Collections.addAll(to, elements);
        }
        return to;
    }
    @Nonnull
    public static <T, C extends Collection<T>> C addAll(@Nonnull C to,
            @Nullable Iterable<T> elements) {
        if (elements != null) {
            try {
                addAll(to, elements.iterator());
            } finally {
                ResourceUtils.closeQuietlyIfAutoCloseable(elements);
            }
        }
        return to;
    }
    @Nonnull
    public static <T, C extends Collection<T>> C addAll(@Nonnull C to,
            @Nullable Iterator<T> elements) {
        if (elements != null) {
            try {
                while (elements.hasNext()) {
                    to.add(elements.next());
                }
            } finally {
                ResourceUtils.closeQuietlyIfAutoCloseable(elements);
            }
        }
        return to;
    }
}

Related Tutorials