Monday 18 May 2015

How to shuffle elements in LinkedList

import java.util.Collections;
import java.util.LinkedList;

public class Shuffle {

    public static void main(String[] args) {
       
        LinkedList<String> linkedList = new LinkedList<String>();
       
        linkedList.add("Mumbai");
        linkedList.add("Delhi");
        linkedList.add("Noida");
        linkedList.add("Gao");
        linkedList.add("Patna");
        //print linkedlist
        System.out.println("Linklist is = "+linkedList);
       
        //Randomly permutes the specified list using a default
         //source of randomness.
       
        Collections.shuffle(linkedList);

        for (String str : linkedList) {
            System.out.println(str);
        }
   
        Collections.shuffle(linkedList);
       
        System.out.println("After Second Shuffle");
       
        for (String str : linkedList) {

            System.out.println(str);

        }
       
    }   
   
}

Output:

Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]

Gao
Noida
Mumbai
Patna
Delhi

After Second Shuffle

Noida
Patna
Gao
Mumbai
Delhi

No comments:

Post a Comment