Java Reference
In-Depth Information
Shuffling, Reversing, Swapping, and Rotating a List
In this section, I will discuss applying different kinds of algorithms to a
List
such as shuffling , reversing, swapping,
and rotating its elements.
Shuffling gives you a random permutation of the elements in a
List
. The concept of shuffling elements of a
List
is the same as shuffling a deck of cards. You shuffle the elements of a
List
by using the
Collections.shuffle()
static
method. You can supply a
java.util.Random
object or the
shuffle()
method can use a default randomizer. The two
versions of the
shuffle()
methods are as follows:
void shuffle(List<?> list)
•
void shuffle(List<?> list, Random rnd)
•
Reversing is the algorithm that puts the elements of a
List
in the reverse order. You can use the following
reverse()
static method of the Collections class to accomplish this:
void reverse(List<?> list)
Swapping lets you swap the position of two elements in a
List
. You can perform swapping using the
swap()
static
method of the
Collections
class, which is defined as follows:
•
void swap(List<?> list, int i, int j)
Here
i
and
j
are indexes of two elements to be swapped and they must be between
0
and
size - 1
, where
size
is
the size of the
List
. Otherwise, it throws an
IndexOutOfBoundsException
.
Rotating involves moving all elements of a
List
forward or backward by a distance. Suppose you have a
List
as
[a, b, c, d]
. You need to visualize that the
List
is a circular list and its first element is next to its last element. If you
rotate this
List
by a distance of 1, the resulting
List
becomes
[d, a, b, c]
. If you rotate the
[a, b, c, d]
list by
a distance of 2, the
List
becomes
[c, d, a, b]
. You can also rotate a
List
backwards by using a negative distance.
If you rotate the
[a, b, c, d]
list by a distance of -2, the
List
becomes
[c, d, a, b]
. You can also rotate only part
of a
List
using a sublist view. Suppose
list
is a reference variable of type
List
and it has
[a, b, c, d]
elements.
Consider executing the following statement:
•
Collections.rotate(list.subList(1, 4), 1);
The statement will change the list to
[a, d, b, c]
. Note that
list.subList(1, 4)
returns a view of
[b, c, d]
elements and the above statement rotates only the three elements that are in the sublist.
The following snippet of code shows how to reorder elements of a
List
using these methods. You may get a
different output when you run the following code because
shuffle()
uses a random algorithm to shuffle the elements
of the
List
.
List<String> list = new ArrayList<>();
list.add("John");
list.add("Richard");
list.add("Donna");
list.add("Ken");
System.out.println("List: " + list);
// Shuffle
Collections.shuffle(list);
System.out.println("After Shuffling: " + list);