How to randomly pick an element from an array

前端 未结 12 727
逝去的感伤
逝去的感伤 2020-11-22 16:48

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?

相关标签:
12条回答
  • 2020-11-22 16:53

    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.

    0 讨论(0)
  • 2020-11-22 16:57

    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();
            }
    
        }
    
    0 讨论(0)
  • 2020-11-22 17:03

    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!

    0 讨论(0)
  • 2020-11-22 17:03
    package io.github.baijifeilong.tmp;
    
    import java.util.concurrent.ThreadLocalRandom;
    import java.util.stream.Stream;
    
    /**
     * Created by BaiJiFeiLong@gmail.com at 2019/1/3 下午7:34
     */
    public class Bar {
        public static void main(String[] args) {
            Stream.generate(() -> null).limit(10).forEach($ -> {
                System.out.println(new String[]{"hello", "world"}[ThreadLocalRandom.current().nextInt(2)]);
            });
        }
    }
    
    0 讨论(0)
  • 2020-11-22 17:04

    use java.util.Random to generate a random number between 0 and array length: random_number, and then use the random number to get the integer: array[random_number]

    0 讨论(0)
  • 2020-11-22 17:05

    You can also use

    public static int getRandom(int[] array) {
        int rnd = (int)(Math.random()*array.length);
        return array[rnd];
    }
    

    Math.random() returns an double between 0.0 (inclusive) to 1.0 (exclusive)

    Multiplying this with array.length gives you a double between 0.0 (inclusive) and array.length (exclusive)

    Casting to int will round down giving you and integer between 0 (inclusive) and array.length-1 (inclusive)

    0 讨论(0)
提交回复
热议问题