随机获取一个集合(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 ...
随机推荐
- 通过DOM实现点击隐藏父元素
HTML代码简单如下: <ul id='ul1'> <li><a href="javascript:">1</a></li&g ...
- python3爬取豆瓣排名前250电影信息
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : doubanmovie.py # @Author: Anthony.waa # @Dat ...
- halcon 模板匹配 -- find_shape_model
find_shape_model(Image : : //搜索图像 ModelID, //模板句柄 AngleStart, // 搜索时的起始角度 AngleExtent, //搜索时的角度范围, ...
- ROS:Nvidia Jetson TK1开发平台
原文链接: http://wiki.ros.org/NvidiaJetsonTK1 1. Nvidia Jetson TK1 Jetson TK1 comes pre-installed with L ...
- ROS: Ubuntu16.04安装ROS-kinetic
参考连接:SLAM: Ubuntu14.04_Kylin安装ROS-Indigo第一步: 软件源配置 1. 增加下载源(增加ubuntu版的ros数据仓库,即下载源)(通用指令适合任何版本的ros) ...
- (转)PJAX的实现与应用
一.前言 web发展经历了一个漫长的周期,最开始很多人认为Javascript这们语言是前端开发的累赘,是个鸡肋,那个时候人们还享受着从一个a链接蹦到另一个页面的web神奇魔术.后来随着JavaScr ...
- php常用字符串和例子
//输出一个或多个字符串 //注:echo 不是一个函数(它是一个语言结构), 因此你不一定要使用小括号来指明参数,单引号,双引号都可以 $a = "admin1"; $b = & ...
- PAT_A1155#Heap Paths
Source: PAT A1155 Heap Paths (30 分) Description: In computer science, a heap is a specialized tree-b ...
- PAT_A1120#Friend Numbers
Source: PAT A1120 Friend Numbers (20 分) Description: Two integers are called "friend numbers&qu ...
- 【VIP视频网站项目一】搭建视频网站的前台页面(导航栏+轮播图+电影列表+底部友情链接)
首先来直接看一下最终的效果吧: 项目地址:https://github.com/xiugangzhang/vip.github.io 在线预览地址:https://xiugangzhang.githu ...