随机获取一个集合(List, Set)中的元素,随机获取一个Map中的key或value
利用Java提供的Random类。从List或Set中随机取出一个元素,从Map中随机获取一个key或value。
因为Set没有提供get(int index)方法,仅仅能先获取一个随机数后。利用一个计数器,对Set进行循环,当计数器等于随机数时返回当前元素,对于Map的处理也类似。
不知有没有更好的方法……
package com.xjj.util; import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom; /**
* 随机数工具,单例模式
* @author XuJijun
*
*/
public class RandomUtils {
//private static Random random; //双重校验锁获取一个Random单例
public static ThreadLocalRandom getRandom() {
return ThreadLocalRandom.current();
/*if(random==null){
synchronized (RandomUtils.class) {
if(random==null){
random =new Random();
}
}
} return random;*/
} /**
* 获得一个[0,max)之间的随机整数。
* @param max
* @return
*/
public static int getRandomInt(int max) {
return getRandom().nextInt(max);
} /**
* 获得一个[min, max]之间的随机整数
* @param min
* @param max
* @return
*/
public static int getRandomInt(int min, int max) {
return getRandom().nextInt(max-min+1) + min;
} /**
* 获得一个[0,max)之间的长整数。
* @param max
* @return
*/
public static long getRandomLong(long max) {
return getRandom().nextLong(max);
} /**
* 从数组中随机获取一个元素
* @param array
* @return
*/
public static <E> E getRandomElement(E[] array){
return array[getRandomInt(array.length)];
} /**
* 从list中随机取得一个元素
* @param list
* @return
*/
public static <E> E getRandomElement(List<E> list){
return list.get(getRandomInt(list.size()));
} /**
* 从set中随机取得一个元素
* @param set
* @return
*/
public static <E> E getRandomElement(Set<E> set){
int rn = getRandomInt(set.size());
int i = 0;
for (E e : set) {
if(i==rn){
return e;
}
i++;
}
return null;
} /**
* 从map中随机取得一个key
* @param map
* @return
*/
public static <K, V> K getRandomKeyFromMap(Map<K, V> map) {
int rn = getRandomInt(map.size());
int i = 0;
for (K key : map.keySet()) {
if(i==rn){
return key;
}
i++;
}
return null;
} /**
* 从map中随机取得一个value
* @param map
* @return
*/
public static <K, V> V getRandomValueFromMap(Map<K, V> map) {
int rn = getRandomInt(map.size());
int i = 0;
for (V value : map.values()) {
if(i==rn){
return value;
}
i++;
}
return null;
} /**
* 生成一个n位的随机数,用于验证码等
* @param n
* @return
*/
public static String getRandNumber(int n) {
String rn = "";
if (n > 0 && n < 10) {
//Random r = new Random();
StringBuffer str = new StringBuffer();
for (int i = 0; i < n; i++) {
str.append('9');
}
int num = Integer.parseInt(str.toString());
while (rn.length() < n) {
rn = String.valueOf(ThreadLocalRandom.current().nextInt(num));
}
} else {
rn = "0";
}
return rn;
} public static void main(String[] args) {
/*Set<String> set = new HashSet<>();
for (int i = 0; i < 12; i++) {
set.add("I am: " + i);
} for (int i = 0; i < 10; i++) {
System.out.println(getRandomElement(set));
}*/ System.out.println(getRandom().nextInt(-100, 10));
}
}
随机获取一个集合(List, Set)中的元素,随机获取一个Map中的key或value的更多相关文章
- 递归算法之排列组合-求一个集合S的m个元素的组合和所有可能的组合情况
求一个集合S的m个元素组合的所有情况,并打印出来,非常适合采用递归的思路进行求解.因为集合的公式,本身就是递归推导的: C(n,m) = C(n-1,m-1) + C(n-1,m). 根据该公式,每次 ...
- 用最小的空间复杂度找出一个长度为n的数组且数据中的元素是[0,n-1]中任一个重复的数据。
用最小的空间复杂度找出一个长度为n的数组且数据中的元素是[0,n-1]中任一个重复的数据. 比如:[1, 2, 3, 3, 2, 2, 6, 7, 8, 9] 中 2 or 3 分析:这道题目,实现比 ...
- O(n) 取得数组中每个元素右边最后一个比它大的元素
题目 2019.9.7,icpc徐州网络赛的E题 XKC's basketball team ,计蒜客上还可以做. 链接:https://nanti.jisuanke.com/t/41387 Inpu ...
- golang中的slice翻转存在以及map中的key判断
//slice翻转 func stringReverse(src []string){ if src == nil { panic(fmt.Errorf("the src can't be ...
- Java中让fastJson识别Colloction和Map中的泛型类
由于fastJson的高效性,最近采用fastJson来做序列化并存储数据,但出现了一个麻烦的问题,如果将Map<K,V>这样的类型序列化,反序列化就会不尽人意,有以下尝试: 使用JSON ...
- Map java中的map 如何修改Map中的对应元素
Map java中的map 如何修改Map中的对应元素 Map以按键/数值对的形式存储数据,和数组非常相似,在数组中存在的索引,它们本身也是对象. Map的接口 Map ...
- Java分享笔记:使用entrySet方法获取Map集合中的元素
/*--------------------------------- 使用entrySet方法取出Map集合中的元素: ....该方法是将Map集合中key与value的关系存入到了Set集合中,这 ...
- 使用Arraylist将数组中元素随机均等乱序分为N个子数组
使用Arraylist将数组中元素随机均等乱序分为N个子数组 觉得有用的话,欢迎一起讨论相互学习~Follow Me 为了将数组中的元素 随机地 ,均等地, 不重复地 ,划分到N个子数组中 使用Arr ...
- ShuffleElements(随机打乱数组中的元素)
给定一个数组,随机打乱数组中的元素,题意很简单直接上代码: package Array; import java.util.Arrays; import java.util.Collections; ...
- 从值栈获取List集合
-------------------siwuxie095 从值栈获取 List 集合 1.具体步骤 (1)在 Action 中向值栈放 List 集合 (2)在 JSP 页面中从值栈获取 List ...
随机推荐
- Docker 常用命令和命令集结
常用命令 查看版本 docker version 查看系统信息 docker info 显示 Docker 系统信息,包括镜像和容器数. 搜索镜像 docker search keyword 从 Do ...
- golang——(strings包)常用字符串操作函数
(1)func HasPrefix(s, prefix string) bool 判断字符串s是否有前缀字符串prefix: (2)func HasSuffix(s, suffix string) b ...
- cocos creator制作微信小游戏
2019-05-30 22:11:47 基础: javaScript基础 https://www.bilibili.com/video/av34087791?from=search&sei ...
- Hbuilder 移动app
==========代码行快捷方法========== div*4div[class=""]*4div[id=""]*4 tr*4tr{<div>w ...
- shell 实用命令学习
查找文件 -iname 大小写不敏感 “*.log” .log后缀的文件 -type d 文件类型为目录的 find ./ -name 'index.html' 查找当前目录,及其子目录下文件
- css2.0文档查阅及字体样式
css2.0文档查阅下载 网址:http://soft.hao123.com/soft/appid/9517.html <html xmlns="http://www.w3.o ...
- 删除django
1.命令行运行python 2.import django3.print(django.__path__)4.删除django目录即可
- YOLO训练Pedestrain
Pedestrain dl 使用darknet训练: 1. Inria 创建 yolo-inria.cfg 从cfg/yolo-voc.2.0.cfg拷贝一份,修改batch=64, subdivi ...
- php数据库批量删除
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...
- Ad hoc polymorphism
与面向对象中的接口类或抽象类中定义的函数组类似: 函数的具体执行依赖与函数医用的类型. In programming languages, ad-hoc polymorphism[1] is a ki ...