Java Collection Convert toUnmodifiableCollection( AnyCollection collection)

Here you can find the source of toUnmodifiableCollection( AnyCollection collection)

Description

Transforms the collection to an unmodifiable one, if there is any implementation in the Java Collections utilities.

License

Open Source License

Parameter

Parameter Description
AnyCollection the type of collection
collection the collection

Return

the collection

Declaration

@SuppressWarnings("unchecked")
public static <AnyCollection extends Collection<?>> AnyCollection toUnmodifiableCollection(
        AnyCollection collection) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

import java.util.List;

import java.util.NavigableSet;

import java.util.Set;

import java.util.SortedSet;

public class Main {
    /**/*from w w w  . j a  va 2 s.c om*/
     * Transforms the collection to an unmodifiable one, if there is any implementation in the Java {@link Collections}
     * utilities.
     *
     * @param <AnyCollection> the type of collection
     * @param collection the collection
     * @return the collection
     */
    @SuppressWarnings("unchecked")
    public static <AnyCollection extends Collection<?>> AnyCollection toUnmodifiableCollection(
            AnyCollection collection) {
        if (collection == null) {
            return null;
        }

        if (collection instanceof List<?>) {
            return (AnyCollection) Collections.unmodifiableList((List<?>) collection);
        }

        if (collection instanceof NavigableSet<?>) {
            return (AnyCollection) Collections.unmodifiableNavigableSet((NavigableSet<?>) collection);
        }

        if (collection instanceof SortedSet<?>) {
            return (AnyCollection) Collections.unmodifiableSortedSet((SortedSet<?>) collection);
        }

        if (collection instanceof Set<?>) {
            return (AnyCollection) Collections.unmodifiableSet((Set<?>) collection);
        }

        return (AnyCollection) Collections.unmodifiableCollection(collection);
    }
}

Related

  1. toStringColl(Collection set)
  2. toSV(Collection collection, String separator)
  3. toTestParameters(Collection rawParams)
  4. toToolTip(final Collection collection)
  5. toTreeSet(Collection collection, Comparator comparator)
  6. trimCollection(Collection collectionToBeConverted)