Java Collection to List toList(Collection collection)

Here you can find the source of toList(Collection collection)

Description

Converts a collection to a list, either by casting or by explicit conversion.

License

Apache License

Parameter

Parameter Description
collection The collection to convert to a list.
T The element type of the collection.

Return

The list representing the elements of the collection.

Declaration

public static <T> List<T> toList(Collection<T> collection) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    /**//from   w  w  w .  j av  a  2 s .c o  m
     * Converts a collection to a list, either by casting or by explicit conversion.
     *
     * @param collection The collection to convert to a list.
     * @param <T>        The element type of the collection.
     * @return The list representing the elements of the collection.
     */
    public static <T> List<T> toList(Collection<T> collection) {
        return collection instanceof List ? (List<T>) collection : new ArrayList<T>(collection);
    }

    /**
     * Converts an iterable to a list, either by casting or by explicit conversion.
     *
     * @param iterable The iterable to convert to a list.
     * @param <T>      The element type of the collection.
     * @return The list representing the elements of the iterable.
     */
    public static <T> List<T> toList(Iterable<T> iterable) {
        if (iterable instanceof Collection) {
            return toList((Collection<T>) iterable);
        } else {
            List<T> list = new LinkedList<T>();
            for (T element : iterable) {
                list.add(element);
            }
            return list;
        }
    }
}

Related

  1. toList(Collection c)
  2. toList(Collection collection)
  3. toList(Collection lines)
  4. toList(Collection c)
  5. toList(Collection c)