How to randomly pick an element from an array

2019-01-01 05:31发布

I am looking for solution to pick number randomly from an integer array.

For example I have an array new int[]{1,2,3}, how can I pick a number randomly?

标签: java
11条回答
千与千寻千般痛.
2楼-- · 2019-01-01 06:10

Since you have java 8, another solution is to use Stream API.

new Random().ints(1, 500).limit(500).forEach(p -> System.out.println(list[p]));

Where 1 is the lowest int generated (inclusive) and 500 is the highest (exclusive). limit means that your stream will have a length of 500.

 int[] list = new int[] {1,2,3,4,5,6};
 new Random().ints(0, list.length).limit(10).forEach(p -> System.out.println(list[p])); 

Random is from java.util package.

查看更多
何处买醉
3楼-- · 2019-01-01 06:14

Take a look at this question:

How do I generate random integers within a specific range in Java?

You will want to generate a random number from 0 to your integers length - 1. Then simply get your int from your array:

myArray[myRandomNumber];
查看更多
萌妹纸的霸气范
4楼-- · 2019-01-01 06:14
package workouts;

import java.util.Random;

/**
 *
 * @author Muthu
 */
public class RandomGenerator {
    public static void main(String[] args) {
     for(int i=0;i<5;i++){
         rndFunc();
     } 
    }
     public static void rndFunc(){
           int[]a= new int[]{1,2,3};
           Random rnd= new Random();
           System.out.println(a[rnd.nextInt(a.length)]);
       }
}
查看更多
梦寄多情
5楼-- · 2019-01-01 06:17

Use the Random class:

int getRandomNumber(int[] arr)
{
  return arr[(new Random()).nextInt(arr.length)];
}
查看更多
皆成旧梦
6楼-- · 2019-01-01 06:18

Java has a Random class in the java.util package. Using it you can do the following:

Random rnd = new Random();
int randomNumberFromArray = array[rnd.nextInt(3)];

Hope this helps!

查看更多
流年柔荑漫光年
7楼-- · 2019-01-01 06:18

You can also try this approach..

public static <E> E[] pickRandom_(int n,E ...item) {
        List<E> copy = Arrays.asList(item);
        Collections.shuffle(copy);
        if (copy.size() > n) {
            return (E[]) copy.subList(0, n).toArray();
        } else {
            return (E[]) copy.toArray();
        }

    }
查看更多
登录 后发表回答