com.github.phantomthief.failover.util.RandomListUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of simple-failover Show documentation
Show all versions of simple-failover Show documentation
A simple failover library for Java
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;
}
}