Sunday 10 May 2015

How to shuffle elements in ArrayList

import java.util.ArrayList;
import java.util.Collections;

public class Shuffle {

    public static void main(String[] args) {
        ArrayList<String> arr = new ArrayList<String>();
        // add element in arraylist
        arr.add("c");
        arr.add("php");
        arr.add("html");
        arr.add("java");
        // print arraylist
        System.out.println("arrayList is = " + arr);
       
        /*
         * Randomly permutes the specified list using a default
           source of randomness
         */
       
        Collections.shuffle(arr);
       
        for (String el : arr) {
            System.out.println(el);
        }
       
        Collections.shuffle(arr);
       
        System.out.println("Second Time shuffle");
        for (String el : arr) {
            System.out.println(el);
        }
       
    }
}

Output:

arrayList is = [c, php, html, java]

java
c
php
html

Second Time shuffle

php
java
html
c


Related Posts: 

 


Storing Java Object In ArrayList





No comments:

Post a Comment