com.alibaba.tmq.common.util.RandomUtil Maven / Gradle / Ivy
package com.alibaba.tmq.common.util;
import java.util.List;
import java.util.Map;
import java.util.Random;
import com.alibaba.tmq.common.constants.Constants;
/**
* Random相关工具
* @author tianyao.myc
*
*/
public class RandomUtil implements Constants {
/** 随机生成数字 */
public static final Random random = new Random();
/**
* 随机获取列表里元素
* objectList
*
*/
public static T getRandomObject4List(List objectList) {
if(null == objectList || objectList.size() <= 0) {
return null;
}
int index = random.nextInt() % objectList.size();
return objectList.get(Math.abs(index));
}
/**
* 随机获取Map里元素
* objectMap
*
*/
@SuppressWarnings("unchecked")
public static V getRandomObject4Map(Map objectMap) {
if(null == objectMap || objectMap.size() <= 0) {
return null;
}
int index = Math.abs(random.nextInt()) % objectMap.size();
return (V)objectMap.values().toArray()[index];
}
/**
* 随机获取Map里元素的Entry
* objectMap
*
*/
@SuppressWarnings("unchecked")
public static Map.Entry getRandomEntry4Map(Map objectMap) {
if(null == objectMap || objectMap.size() <= 0) {
return null;
}
int index = Math.abs(random.nextInt()) % objectMap.size();
return (Map.Entry)objectMap.entrySet().toArray()[index];
}
/**
* 获取随机索引
* objectList
*
*/
public static int getRandomIndex(List extends Object> objectList) {
if(null == objectList || objectList.size() <= 0) {
return -1;
}
int index = random.nextInt() % objectList.size();
return Math.abs(index);
}
}