How To Shuffle String Arrays

13,417

Solution 1

If you task isn’t implementation of the snuffle algorithm you can use standard java.util.Collections#shuffle method:

String[] firstName = new String[] {"a","b","c","d","e"};
List<String> strList = Arrays.asList(firstName);
Collections.shuffle(strList);
firstName = strList.toArray(new String[strList.size()]);

Solution 2

just create an array (or list) which has the values

Integer[] arr = new Integer[firstName.length];
for (int i = 0; i < arr.length; i++) {
    arr[i] = i;
}

Collections.shuffle(Arrays.asList(arr));

and then just create a new string array to move the values into

string[] newFirstName = new string[arr.length]();
for(int i=0; i < arr.length; i++)
{
    newFirstName[i] = firstName[arr[i]];
    //etc ....
}
Share:
13,417
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    How Can I Shuffle below array

    String[] firstName =["a","b","c","d","e"];
    String[] lastName =["p","q","r","s","t"];
    String[] salary =["10","20","30","40",50"];
    String[] phoneNo= ["1","2","3","4","5"];
    

    after shuffling the array i need result like

    String[] firstName =["d","b","e","c","a"];
    String[] lastName =["s","q","t","r","p"];
    String[] salary =["40","20","50","30",10"];
    String[] phoneNo= ["4","2","5","3","1"];
    

    means for example if index of "a" from firstName Changes from 0 to 4, respective index of "p","10","1" to be changed from 0 to 4..

  • Admin
    Admin about 8 years
    What if my Array is of X length....??
  • Grant Nilsson
    Grant Nilsson about 8 years
    well all of the examples you used above were using the same sorting order. so i assumed you had a set order and length. does the shuffle need to be random?
  • Admin
    Admin about 8 years
    thats what i need for arrays of Unknown some X length
  • Grant Nilsson
    Grant Nilsson about 8 years
    if you need to randomize the list then see the comments above from others
  • Admin
    Admin about 8 years
    thanks for ur answer but i have got solution for it