How To Generate Two Random Int Arrays In Java
We want to generate two random arrays of the same size in Java. I think the best and clean way of doing this is with IntStream and Random.
When a user starts our program, we ask them to enter the array size they want.
Then we go ahead and generate the array:
//java import java.util.Arrays; import java.util.Random; import java.util.stream.IntStream; import java.util.Scanner; import textio.TextIO; public class GenerateRandomIntArrays { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println(("Enter array size: ")); int size = scanner.nextInt(); int[] randomIntOne = IntStream.generate(() -> new Random().nextInt(100)).limit(size).toArray(); int[] randomIntTwo = IntStream.generate(() -> new Random().nextInt(100)).limit(size).toArray(); System.out.println(Arrays.toString(randomIntOne)); System.out.println(Arrays.toString(randomIntTwo)); } }
And the result:
Enter array size: 5 [23, 55, 74, 61, 84] [87, 37, 14, 99, 75]