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?
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?
Since you have java 8, another solution is to use Stream API.
Where
1
is the lowest int generated (inclusive) and500
is the highest (exclusive).limit
means that your stream will have a length of 500.Random is from
java.util
package.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:
Use the Random class:
Java has a Random class in the java.util package. Using it you can do the following:
Hope this helps!
You can also try this approach..