List rotating and shuffling

In this chapter you will learn:

  1. Rotate and shuffle a list
  2. Rotate a list

Rotate and shuffle a list

Shuffling a List is useful when we want to change the order of elements in a list. For example, we can output random sequence of a list of string by shuffling the list each time.

  • static void rotate(List<?> list, int distance) Rotates the elements in the specified list by the specified distance.
  • static void shuffle(List<?> list) Randomly permutes the specified list using a default source of randomness.
  • static void shuffle(List<?> list, Random rnd) Randomly permute the specified list using the specified source of randomness.
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/* java2  s.c  o  m*/
public class Main {

  public static void main(String args[]) {
    List<Character> list = new LinkedList<Character>();

    for (char n = 'A'; n <= 'Z'; n++)
      list.add(n);

    Collections.shuffle(list);

    System.out.print(list);

  }
}

The output:

Rotate a list

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/*from  j a  v  a2  s  . c o  m*/
public class Main {
  public static void main(String args[]) {
    List<Character> list = new LinkedList<Character>();

    for (char n = 'A'; n <= 'F'; n++)
      list.add(n);

    System.out.println("Here is the original list: ");
    System.out.println(list);
    Collections.rotate(list, 2);

    System.out.println(list);

  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to Sort a list
  2. Sort elements of ArrayList
  3. Sort elements of Vector
  4. Sort ArrayList in descending order using comparator
Home » Java Tutorial » List

List

    List interface
    List add/insert elements
    List clear/remove elements
    List search
    List element get and set
    List and its Iterator
    List size, empty
    List conversion, to array
    List to sublist
    List comparison
    List filling
    List reversing
    List rotating and shuffling
    List sorting
    List element swap
    List element replacing
    List copy
    List binary search

ArrayList

    ArrayList
    ArrayList Creation
    ArrayList add/insert
    ArrayList get/set element
    ArrayList clear/remove
    ArrayList search
    ArrayList copy and shallow copy
    ArrayList size, trim to size and capacity
    ArrayList to array

LinkedList

    LinkedList class
    LinkedList creation
    LinkedList add/insert elements
    LinkedList get elements
    LinkedList search
    LinkeList replace/set elements
    LinkedList remove element
    LinkedList copy
    LinkedList iterator
    LinkedList peek element
    LinkedList pop/push element
    LinkedList conversion

List Utilities

    List filling
    List reversing
    List rotating and shuffling
    List sorting
    List element swap
    List element replacing
    List copy
    List binary search