2

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..

4
  • 1
    @Sabik JavaScript is not Java. Commented Mar 5, 2016 at 9:12
  • Did you begin with something or are you hoping someone will dump you the code? Commented Mar 5, 2016 at 9:13
  • One of the best ways to accomplish this would be to create a custom object with those 4 String fields. Then you can have a constructor such as MyObject(String fN, String lN, String sal, String pN) and use that to set initial values. Then create an array of MyObject Commented Mar 5, 2016 at 9:14
  • 1
    Sorry, my mistake, see: stackoverflow.com/questions/1519736/… stackoverflow.com/questions/4228975/how-to-randomize-arraylist Commented Mar 5, 2016 at 9:18

2 Answers 2

10

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()]);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for ur answer but i have got solution for it
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 ....
}

4 Comments

What if my Array is of X length....??
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?
thats what i need for arrays of Unknown some X length
if you need to randomize the list then see the comments above from others