Shuffle the elements of Java LinkedList - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Friday, December 2, 2016

Shuffle the elements of Java LinkedList

LinkedList is doubly-linked list implementation of the List and Deque interfaces.

How to shuffle elements of Java LinkedList?

This example gives how to shuffled elements in the LinkedList. You can shuffle the content of Java ArrayList by calling Collections.shuffle() method. Every time you call shuffle() method, it generates different order of output.

package com.walking.techie;

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

public class LinkedListShuffleDemo {

 public static void main(String[] args) {
  LinkedList<String> language = new LinkedList<String>();
  language.add("C");
  language.add("CPP");
  language.add("JAVA");
  language.add("DOTNET");
  language.add("C#");
  language.add("PHP");

  System.out.println("Original language linked list " + language);
  Collections.shuffle(language);

  System.out.println("language linked list after shuffled applied " + language);
  Collections.shuffle(language);

  System.out.println("language linked list after shuffled applied " + language);
 }
}

Output of above program is shown below:

Original language linked list [C, CPP, JAVA, DOTNET, C#, PHP]
language linked list after shuffled applied [JAVA, C, PHP, CPP, DOTNET, C#]
language linked list after shuffled applied [DOTNET, C#, PHP, CPP, JAVA, C]

1 comment :

  1. well explained . thanks for sharing good post . Good arraylist example collection visit
    Arraylist example

    ReplyDelete