利用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的更多相关文章

  1. 递归算法之排列组合-求一个集合S的m个元素的组合和所有可能的组合情况

    求一个集合S的m个元素组合的所有情况,并打印出来,非常适合采用递归的思路进行求解.因为集合的公式,本身就是递归推导的: C(n,m) = C(n-1,m-1) + C(n-1,m). 根据该公式,每次 ...

  2. 用最小的空间复杂度找出一个长度为n的数组且数据中的元素是[0,n-1]中任一个重复的数据。

    用最小的空间复杂度找出一个长度为n的数组且数据中的元素是[0,n-1]中任一个重复的数据. 比如:[1, 2, 3, 3, 2, 2, 6, 7, 8, 9] 中 2 or 3 分析:这道题目,实现比 ...

  3. O(n) 取得数组中每个元素右边最后一个比它大的元素

    题目 2019.9.7,icpc徐州网络赛的E题 XKC's basketball team ,计蒜客上还可以做. 链接:https://nanti.jisuanke.com/t/41387 Inpu ...

  4. golang中的slice翻转存在以及map中的key判断

    //slice翻转 func stringReverse(src []string){ if src == nil { panic(fmt.Errorf("the src can't be ...

  5. Java中让fastJson识别Colloction和Map中的泛型类

    由于fastJson的高效性,最近采用fastJson来做序列化并存储数据,但出现了一个麻烦的问题,如果将Map<K,V>这样的类型序列化,反序列化就会不尽人意,有以下尝试: 使用JSON ...

  6. Map java中的map 如何修改Map中的对应元素

    Map java中的map 如何修改Map中的对应元素 Map以按键/数值对的形式存储数据,和数组非常相似,在数组中存在的索引,它们本身也是对象.         Map的接口         Map ...

  7. Java分享笔记:使用entrySet方法获取Map集合中的元素

    /*--------------------------------- 使用entrySet方法取出Map集合中的元素: ....该方法是将Map集合中key与value的关系存入到了Set集合中,这 ...

  8. 使用Arraylist将数组中元素随机均等乱序分为N个子数组

    使用Arraylist将数组中元素随机均等乱序分为N个子数组 觉得有用的话,欢迎一起讨论相互学习~Follow Me 为了将数组中的元素 随机地 ,均等地, 不重复地 ,划分到N个子数组中 使用Arr ...

  9. ShuffleElements(随机打乱数组中的元素)

    给定一个数组,随机打乱数组中的元素,题意很简单直接上代码: package Array; import java.util.Arrays; import java.util.Collections; ...

  10. 从值栈获取List集合

    -------------------siwuxie095 从值栈获取 List 集合 1.具体步骤 (1)在 Action 中向值栈放 List 集合 (2)在 JSP 页面中从值栈获取 List ...

随机推荐

  1. Aspnet_Session

    cmd: aspnet_regsql.exe -ssadd -sstype c -d ZZCasSession -S 192.168.0.3 -U sa -P szhweb2010 <!--会话 ...

  2. python 5:str(某一变量)(将其他数字解释为字符串)

    age = messege = "Your's age is " + str(age) #将其他数字更改为字符串 print(messege) 运行结果应该是: Your's ag ...

  3. springMVC上传图片,json交互(三)

    @RequestMapping 通过@RequestMapping注解可以定义不同的处理器映射规则. @RequestMapping(value="item")或@RequestM ...

  4. 网上找的JS截取字符串(含中文)

    <script> /* 2007-11-28 XuJian */ //截取字符串 包含中文处理 //(串,长度,增加...) function subString(str, len, ha ...

  5. for 循环 乘法口诀表

    用for循环写乘法口诀表: for(var i = 1; i <= 9; i++) { var c=''; for(var x = 1; x <= i; x++) {    c=c+x+' ...

  6. hibernate_07_单表操作_增删改操作

    首先,创建类对象 package com.imooc.hibernate; public class Address { private String postcode; //邮编 private S ...

  7. sqlserver查询分析器在本地服务器查看其它SqlServer服务器内容

    exec sp_addlinkedserver 服务器自命名,'',sqloledb,要查询服务器的IP地址 exec sp_addlinkedsrvlogin 服务器自命名,false,null,账 ...

  8. dubbo之服务分组

    当一个接口有多种实现时,可以用group区分. 服务 <dubbo:service group="feedback" interface="com.xxx.Inde ...

  9. (转)Arcgis for JS之地图自适应调整

    http://blog.csdn.net/gisshixisheng/article/details/42675897 概述:本节讲述的内容为当浏览器大小发生变化或者地图展示区域的大小发生变化时,地图 ...

  10. c# cookie帮助类

    using System; using System.Collections.Generic; using System.Text; using System.Web; namespace Matic ...