To reorder the elements of a List
in Java randomly, you can use the Collections.shuffle
method of the java.util.Collections
class. This method shuffles the elements of the List
in place using a default random number generator.
Here is an example of how you can use the Collections.shuffle
method to shuffle the elements of a List
in Java:
import java.util.Collections; import java.util.List; List<Integer> list = List.of(1, 2, 3, 4, 5); Collections.shuffle(list); System.out.println(list); // Outputs a shuffled list, such as "[5, 2, 4, 1, 3]"
In this example, the Collections.shuffle
method is called on the list
List
object, and it shuffles the elements of the list in place using a default random number generator.
Keep in mind that the Collections.shuffle
method operates on the original List
object and shuffles the elements in-place, without creating a new List
. If you want to create a new List
with the elements shuffled, you can use the stream
API or the collect
method of the Stream
interface to create a new List
from the shuffled elements.
For example:
import java.util.List; import java.util.stream.Collectors; List<Integer> list = List.of(1, 2, 3, 4, 5); List<Integer> shuffledList = list.stream().collect(Collectors.toList()); Collections.shuffle(shuffledList); System.out.println(shuffledList); // Outputs a shuffled list, such as "[5, 2, 4, 1, 3]"
You can also use the shuffle
method of the List
interface (which is implemented by various classes such as ArrayList
and LinkedList
) to shuffle the elements of a List
. This method shuffles the elements of the List
in place using a specified random number generator.
For example:
import java.util.List; import java.util.Random; List<Integer> list = List.of(1, 2, 3, 4, 5); Random random = new Random(); list.shuffle(random); System.out.println(list); // Outputs a shuffled list, such as "[5, 2, 4, 1, 3]"
In this example, the shuffle
method is called on the list
List
object, and it shuffles the elements of the list in place using a specified Random
object.