How to randomly pick an element from an array

前端 未结 12 833
逝去的感伤
逝去的感伤 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.

提交回复
热议问题