Home | Tutorials | Articles | Videos | Products | Tools | Search
 Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact
 Java > Random Numbers > Shuffle

# Shuffle

The following code shows the generation of random numbers with in some range and suffling the user provided list. The logic is that we randomly pick a number from the given range and add to the final list. This process continues util all elements in the range are processed.

 File Name  : com/bethecoder/tutorials/random/Shuffle.java Author  : Sudhakar KV Email  : [email protected]

 ``` package com.bethecoder.tutorials.random; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Shuffle {   public static void main(String[] args) {            List shuffledItems = shuffle(1, 10);     System.out.println(shuffledItems);          List shuffledStringItems = shuffle(Arrays.asList(new String [] {         "one", "two", "three", "four", "five", "six", "seven", "eight"         }));          System.out.println(shuffledStringItems);   }      public static List shuffle(Integer start, Integer count) {          List items =  new ArrayList(count);     List shuffledItems =  new ArrayList(count);          for (int i = 0 ; i < count ; i ++ ) {       items.add(start + i);     }          while (items.size() > 0) {       shuffledItems.add(items.remove((int)(1729 * Math.random()) % items.size()));     }          return shuffledItems;   }      public static List shuffle(List items) {          List shuffledItems = shuffle(0, items.size());     List shuffledStringItems =  new ArrayList(items.size());          for (int i = 0 ; i < shuffledItems.size() ; i ++ ) {       shuffledStringItems.add(items.get(shuffledItems.get(i)));     }          return shuffledStringItems;   } }```

It gives the following output,
```[4, 6, 8, 7, 2, 3, 1, 9, 5, 10]
[five, three, four, six, one, eight, two, seven]

[9, 1, 10, 4, 7, 2, 6, 8, 3, 5]
[five, seven, eight, six, four, three, one, two]
```