import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 随机
 * @author liu08dzxx
 *
 */
public class RandomUtil {

    /**
     * 随机抽取一定数量的指定对象
     * 如果数量等于传入的列表数量,则会随机打乱顺序
     * @param os
     * @param goalNum
     * @return
     */
    public static <T> List<T> random(List<T> os, int goalNum) {
        List<T> newList = Lists.newArrayList();
        // 给每一个对象,随机一个数,然后排序,取前面的目标条数
        Map<Double,T> map = Maps.newLinkedHashMap();
        for(T t : os) {
            map.put(Math.random(), t);
        }
        List<Entry<Double,T>> list = Lists.newArrayList( map.entrySet().iterator());
        Collections.sort(list,new Comparator<Entry<Double,T>>() {
            @Override
            public int compare(Entry<Double, T> o1, Entry<Double, T> o2) {
                if(o1.getKey().doubleValue()>o2.getKey().doubleValue()) {
                    return 1;
                }else if(o1.getKey().doubleValue()<o2.getKey().doubleValue()) {
                    return -1;
                }else {
                    return 0;
                }

            }
        });
        int i = 0;
        for(Entry<Double,T> e :  list) {
            newList.add(e.getValue());
            i++;
            if(i>=goalNum) {
                break;
            }
            
        }
       return newList;
    }
    
    /**
     * 随机生成整数,最小为0,最大为maxValue-1
     * @param maxValue
     * @return
     */
    public static int randomNum(int maxValue) {
        Random rand = new Random();  
        
      return rand.nextInt(maxValue);
     
    }
    
    public static void main(String[] args) {
       List<Integer> list = Lists.newArrayList(new Integer[] {1,2,3,4,5,6,7,8,9,10});
       for(int i =0;i<10;i++) {
           System.out.println(JSON.toJSONString(random(list, 10)));
       }
    }
    
    /**
     * 随机取一个
     * @return
     */
    public static <T> T randomOne(List<T> os) {
        return random(os, 1).get(0);
    }
    

    /**
     * 随机返回true和false
     * @return
     */
    public static boolean randomBoolean() {
        double num = Math.random();
        if (num > 0.5d) {
            return true;
        } else {
            return false;
        }
    }
    
    

}

 

posted on 2020-09-22 18:08  菜鸟你够了  阅读(444)  评论(0编辑  收藏  举报