Collections

how to shuffle the elements of a LinkedList using Collections in java
Previous Home Next

 

In this example we will see how can we shuffle the elements of a LinkedList.

In this example we have created a class CollectionExample. For using LinkedList we have
to import the java.util package.
 In this example we have created a LinkedList object. Then we passed this object to the shuffle() method defined in the Collections class. The shuffle takes the two parameters viz.

shuffle(List obj, Random obj);
This method takes the List object and Random class object as its parameters.

In this example firstly we have created a class named CollectionExample. Inside this class we have created  a LinkedList named list and added some elements to it. Then we have passed this object with Random class object to the shuffle method defined and AbstractCollection class, which results in the random display of the elements of the list. The following statement of the example does that,

Collections.shuffle(list, new Random());

 
package r4r.co.in;
import java.util.*;
import java.util.ListIterator;


public class CollectionExample {

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub


LinkedList<Object> list=new LinkedList<Object>(); // creating a LinkedList of Object type elements
list.add(1); // adding integer values to the LinkedList
list.add(2);
list.add("r4r"); // adding String values to the LinkedList
list.add("shashi");
list.add("s/w engineer");

ListIterator<Object> ltr=list.listIterator(); // Invoking the ListIterator on the list for iterating through the list
System.out.println("Before shuffling the list is :");
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the contents of the list
}

Collections.shuffle(list, new Random()); // shuffliing the contents of the list by using the shuffle() method

System.out.println("After shuffling the list elements are as follows: ");
ltr=list.listIterator();
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the shuffled list
}

}


}
The output of the above written code is as follows:

Before shuffling the list is :
1
2
r4r
shashi
s/w engineer
After shuffling the list elements are as follows:
2
shashi
1
r4r
s/w engineer
Previous Home Next