randomize Collection and return a List - Java java.util

Java examples for java.util:Collection Search

Description

randomize Collection and return a List

Demo Code


//package com.java2s;
import java.util.*;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "java2s.com");
        System.out.println(randomList(collection));
    }/*w w w . j a v  a2 s.  c o  m*/

    public static <E> List<E> randomList(Collection<E> collection) {

        List<E> list = new ArrayList<>(collection);
        Collections.shuffle(list);

        return list;
    }

    public static <E> List<E> randomList(E[] elements) {

        return randomList(Arrays.asList(elements));
    }

    public static <E> List<E> asList(E[] array) {
        if (isEmpty(array)) {
            return new ArrayList<>();
        }

        return Arrays.asList(array);
    }

    private static <E> boolean isEmpty(Collection<E> collection) {

        return (collection == null || collection.isEmpty());
    }

    private static <E> boolean isEmpty(E[] array) {

        return (array == null || array.length == 0);
    }
}

Related Tutorials