集合(List,Set)の要素をランダムに取得し、Mapのkeyまたはvalueをランダムに取得します.
Javaが提供するRandomクラスを利用して、ListまたはSetから要素をランダムに取り出し、Mapからkeyまたはvalueをランダムに取得します.
Setはget(int index)メソッドを提供していないため,まず1つの乱数を取得した後,1つのカウンタを用いてSetをループし,カウンタが乱数に等しい場合に現在の要素を返し,Mapに対する処理も同様である.もっといい方法があるかどうか・・・
Setはget(int index)メソッドを提供していないため,まず1つの乱数を取得した後,1つのカウンタを用いてSetをループし,カウンタが乱数に等しい場合に現在の要素を返し,Mapに対する処理も同様である.もっといい方法があるかどうか・・・
package com.xjj.util;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* ,
* @author XuJijun
*
*/
public class RandomUtils {
private static Random random;
// Random
public static Random getRandom() {
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 Math.abs(getRandom().nextInt())%max;
}
/**
* [0,max) 。
* @param max
* @return
*/
public static long getRandomLong(long max) {
return Math.abs(getRandom().nextInt())%max;
}
/**
* 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;
}
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));
}
}
}