Tuesday, 12 November 2013

How to shuffle elements in ArrayList?

Here is a single line code that lets you shuffle elements in an ArrayList. The method shuffle() in the Collections class lets you do this. Note that the line you write is no more than single line, there are a lot of lines written in the shuffle() method ;)


import java.util.*;
class ShuffleElements
{
    public static void main(String args[])
    {
        // Do nothing, if no arguments < 2
        if(args.length<2) return;
      
        // Create an array list containing the array
        // Arrays.asList() adds the given array to a List
        // and returns that object
        // The second constructor of ArrayList
        ArrayList<String> a=new ArrayList<>(Arrays.asList(args));
      
        // Shuffle the elements
        Collections.shuffle(a);
          
            // Print all of them
            for(int i=0;i<args.length;i++)
            {
                System.out.println(a.get(i));
            }
    }
}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)

“I must complain the cards are ill shuffled till I have a good hand” - Jonathan Swift

No comments:

Post a Comment