Rotate and shuffle a list
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;
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:
[L, B, P, U, K, C, O, W, Y, T, G, R, Z, J, I, N, S, A, Q, D, H, X, F, M, E, V]
Shuffle elements in ArrayList
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("java2s.com");
System.out.println("Before shuffling: " + arrayList);
Collections.shuffle(arrayList);
System.out.println("After shuffling: " + arrayList);
}
}
The output:
Before shuffling: [A, B, C, D, java2s.com]
After shuffling: [java2s.com, B, C, A, D]
Shuffle elements of Vector
import java.util.Collections;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector v = new Vector();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("java2s.com");
System.out.println("Before shuffling: " + v);
Collections.shuffle(v);
System.out.println("After shuffling: " + v);
}
}
The output:
Before shuffling: [1, 2, 3, 4, java2s.com]
After shuffling: [3, 4, 2, java2s.com, 1]
Rotate a list
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
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:
Here is the original list:
[A, B, C, D, E, F]
[E, F, A, B, C, D]
Home
Java Book
Collection
Java Book
Collection
Collections:
- Collections
- Get empty collection from Collections
- Do binary search
- Copy value to a List
- Get Enumeration from collection, create list from Enumeration
- Fill a list
- Get the max and min value from a Collection
- Fill n Copy object to a list
- Replace value in a list
- Reverse a list
- Get comparator in reverse order
- Rotate and shuffle a list
- Create singleton
- Sort a list
- Swap element in a list
- Get a synchronized collection
- Return an unmodifiable view of collections