Way2Java

LinkedList Sort Reverse Shuffle Example

In this program, the operations like sorting, shuffling, reversing and printing the elements in the ascending order are done. These are very common operations used by every programmer now and then.

LinkedList Sort Reverse Shuffle Example
import java.util.*;
public class LinkedListSpecial
{
  public static void main(String args[])
  {
    LinkedList myList = new LinkedList();
    myList.add("one");
    myList.add("two");
    myList.add("six");
    myList.add("zero");
    myList.add("nine");
		                 // SORTING IN ASCENDING ORDER
    Collections.sort(myList);
    System.out.println("Sorted elements: " + myList);

		                 // REVERSED ELEMENTS
    Collections.reverse(myList);
    System.out.println("Reversed on sorted elements: " + myList);

		                 // SHUFFLING
    Collections.shuffle(myList);
    System.out.println("\nFirst shuffle elements: " + myList);
    Collections.shuffle(myList);
    System.out.println("Second shuffle elements: " + myList);

    System.out.println("\nnine exists: " + myList.contains("nine"));
  }
}


Output screen of LinkedList Sort Reverse Shuffle

       LinkedList myList = new LinkedList();
       myList.add("one");

A generics linked list object myList is created that stores strings only. With add() method, inherited from Collection interface, a few strings are added.

       Collections.sort(myList);

With static method sort() of Collections class, myList elements are sorted in ascending order automatically.

       Collections.reverse(myList);

With static method reverse() of Collections class, myList elements (existing just before reverse() is called) are reversed.

       Collections.shuffle(myList);

The static method shuffle() of Collections class shuffles myList elements. Calling shuffle() method number of times prints different order of elements.

       System.out.println("\nnine exists: " + myList.contains("nine"));

The contains() method, inherited from Collection interface, checks the element exists or not in the linked list. If the element passed as parameter exists, the method returns true else false. It can be used in the programming like this.

       if(! myList.contains("nine"))
       {
         myList.add("nine");
       }