package com.duben.microtribe.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class SplitArrayUtils {
    /**
     * 随机获取长度为size的list<br>
     * 获取的list顺序也是随机的
     * 截取size比list长或相等,则返回全部
     * @param source
     * @return
     */
    public static <T> List<T> getRandomList(List<T> source){
        int size=source.size();
        if(source.size() <= size){
            Collections.shuffle(source);
            return source;
        }
        List<T> target = new ArrayList<>(size);
        Set<Integer> set = new HashSet<>(size);
        while (set.size() < size){
            int random = new Random().nextInt(source.size());
            if(!set.contains(random)){
                set.add(random);
                target.add(source.get(random));
            }
        }
        return target;

    }
}
