The first way: -
You can also save a List all numbers. Then use Collections.shuffle to shuffle the list and get the first item. And delete it.
List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(4); list.add(2); list.add(3); System.out.println("Original List: " + list); Collections.shuffle(list); System.out.println("Shuffled List: " + list); int number1 = list.remove(0);
OUTPUT : -
Original List: [1, 4, 2, 3] Shuffled List: [4, 3, 1, 2] Number removed: 4 Shuffled List: [1, 3, 2] Number removed: 1
The second way: -
It is best to create a random number from 0 in the size list and get the value that index and delete it.
int size = list.size(); Random random = new Random(); for (int i = 0; i < size; i++) { int index = random.nextInt(list.size()); int number1 = list.remove(index); System.out.println(number1); }
NOTE: - If you want to exclude a specific set of numbers from the generated ones, then you can have these numbers in the list. Then remove all items from this list from the list of numbers . And then use any of the above methods.
source share