Sunday 5 January 2020

Shuffle array lists in same fashion (java)




Using Collections.shuffle
By passing randomizer with same seed to Collections.shuffle function, you can shuffle array lists in same fashion.

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class App {

 private static void printList(List list) {
  for (Object obj : list) {
   System.out.print(obj + " ");
  }
  System.out.println();
 }

 public static void main(String args[]) {
  List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5);
  List<Character> chars = Arrays.asList('a', 'b', 'c', 'd', 'e');

  long seed = System.currentTimeMillis();

  Random rand1 = new Random(seed);
  Random rand2 = new Random(seed);

  Collections.shuffle(ids, rand1);
  Collections.shuffle(chars, rand2);

  printList(ids);
  printList(chars);

 }
}

Output
2 4 3 1 5
b d c a e



You may like

No comments:

Post a Comment