Java Collection How to - Shuffle two arrays








Question

We would like to know how to shuffle two arrays.

Answer

import java.util.Random;
//from   w  w w .j av  a2s .  c o m
public class Main {
    public static void main(String[] args) {
        long[] numbers = new long[]{1,2,3,4,5};
        Random id = new Random(numbers.length);
        
        String[] name = new String[]{"a","b","c","d","e"};

        for (int i = 0; i < numbers.length; i++) {
            int randomPosition = id.nextInt(4);
            long temp = numbers[i];
            numbers[i] = numbers[randomPosition];
            numbers[randomPosition] = temp;
        }

        for (int i = 0; i < name.length; i++) {
            int randomPosition = id.nextInt(4);
            String temp = name[i];
            name[i] = name[randomPosition];
            name[randomPosition] = temp;
        }
        for (int i = 0; i < numbers.length; i++) {
            System.out.println(i + " ID = " + numbers[i] + " and name = " + name[i]);
        }
    }
}

The code above generates the following result.