工作中近期涉及到了抽奖,总结了一个小的权重抽奖工具,分享给大家
/**
* @author hman
* @createTime 2018/7/11
* @description 按照权重自动抽奖并且返回权重
*/
public class WeightUtil {
/**
* @param weights 权重集合 1,2,3,4 ->[1,3,6,10]
* @return random in [1,3,6,10] by weight
*/
public static Optional<Integer> randomCoupons(Collection<Integer> weights) {
if (CollectionUtils.isNotEmpty(weights)) {
ArrayList<Integer> objects = Lists.newArrayList();
weights.forEach(t -> objects.add(t));
Collections.sort(objects);
Random random = new Random();
int i = random.nextInt(objects.get(objects.size() - 1) - 1);
return objects.stream().filter(t -> i <= t).findFirst();
}
return Optional.empty();
}
}
网友评论