All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.phantomthief.failover.util.RandomListUtils Maven / Gradle / Ivy

There is a newer version: 0.1.32
Show newest version
package com.github.phantomthief.failover.util;

import static java.lang.Math.min;
import static java.util.Collections.emptyList;
import static java.util.Collections.shuffle;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.RandomAccess;
import java.util.concurrent.ThreadLocalRandom;

import javax.annotation.Nullable;

/**
 * @author w.vela
 */
public class RandomListUtils {

    private static final int LCG_THRESHOLD = 3;

    private RandomListUtils() {
        throw new UnsupportedOperationException();
    }

    @Nullable
    public static  T getRandom(List source) {
        if (source == null || source.isEmpty()) {
            return null;
        }
        return source.get(ThreadLocalRandom.current().nextInt(source.size()));
    }

    public static  List getRandom(Collection source, int size) {
        if (source == null || source.isEmpty()) {
            return emptyList();
        }
        if (source instanceof List && source instanceof RandomAccess
                && size < source.size() / LCG_THRESHOLD) {
            return getRandomUsingLcg((List) source, size);
        } else {
            return getRandomUsingShuffle(source, size);
        }
    }

    static  List getRandomUsingShuffle(Collection source, int size) {
        List newList = new ArrayList<>(source);
        shuffle(newList, ThreadLocalRandom.current());
        return newList.subList(0, min(newList.size(), size));
    }

    static  List getRandomUsingLcg(List source, int size) {
        int targetSize = min(source.size(), size);
        List newList = new ArrayList<>(targetSize);
        LcgRandomIterator iterator = new LcgRandomIterator<>(source);
        for (int i = 0; i < targetSize; i++) {
            newList.add(iterator.next());
        }
        return newList;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy