Collections Rotate Shuffle And Frequency

Rotate, reverse, shuffle, and count frequencies in lists with the Collections utilities while keeping seeded shuffles reproducible.

JavaData Integrity

Code

snippet
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class CollectionsUtilities {
    public static void main(String[] args) {
        List<Integer> values = new ArrayList<>(List.of(5, 1, 4, 1, 4, 5, 9));
        System.out.println("original: " + values);
        System.out.println("frequency(4): " + Collections.frequency(values, 4));

        // rotate:整体循环右移两位
        Collections.rotate(values, 2);
        System.out.println("rotated: " + values);

        Collections.reverse(values);
        System.out.println("reversed: " + values);
        Collections.swap(values, 0, values.size() - 1);
        System.out.println("swapped: " + values);

        // 固定种子:洗牌顺序可复现
        Collections.shuffle(values, new Random(42));
        System.out.println("shuffled(seed=42): " + values);

        Collections.sort(values);
        System.out.println("sorted: " + values);
        System.out.println("index of 5: " + Collections.binarySearch(values, 5));
        System.out.println("min/max: " + Collections.min(values) + "/" + Collections.max(values));

        // 不可变视图:底层仍可修改,但视图拒绝写入
        List<Integer> view = Collections.unmodifiableList(values);
        try {
            view.add(0);
        } catch (UnsupportedOperationException e) {
            System.out.println("view rejected write: " + e.getClass().getSimpleName());
        }
    }
}

How it works

Collections Rotate Shuffle And Frequency comes down to the class CollectionsUtilities and the function main.

Using it

Each run prints the 10 labeled blocks original:, frequency(4):, rotated:, reversed:, swapped:, shuffled(seed=42):, sorted:, index of 5:, min/max:, view rejected write: in source order.

Key statements

Collections.sort(values);

Interactive Tools for This Topic

FAQ

What does Collections Rotate Shuffle And Frequency print when run?
Running the file directly is enough — expect labeled output lines such as `original:`, `frequency(4):`, `rotated:`.