List rotating and shuffling
In this chapter you will learn:
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;
/*j a v a 2s.c om*/
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 ava 2 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:
- How to Sort a list
- Sort elements of ArrayList
- Sort elements of Vector
- Sort ArrayList in descending order using comparator
Home » Java Tutorial » Collections