Changing the order of the elements of List in random manner

25 / Sep / 2012 by Divya Setia 0 comments

I found a very interesting method in java to change the order of elements in a list randomly, also called shuffling of elements in list.

Actually I got the requirement to show a random product details out of 5 products, each time user refreshes the page. I came out with the solution using Collections.shuffle(<list>)

For understanding, lets assume, we have Product class. Each product has a name and its corresponding price.

[java]
class Product{
String name
Float price
}

// Six different products
Product product1 = new Product(name:"TV",price:30000)
Product product2 = new Product(name:"Refrigerator",price:20000)
Product product3 = new Product(name:"Radio",price:2000)
Product product4 = new Product(name:"Washing Machine",price:20000)
Product product5 = new Product(name:"Fan",price:1000)
Product product6 = new Product(name:"AC",price:20000)

//List of above products
List products = [product1,product2,product3,product4,product5,product6]

println products*.name
//Output : [TV, Refrigerator, Radio, Washing Machine, Fan, AC]

Collections.shuffle(products)

println products*.name
// Output : [Washing Machine, Refrigerator, AC, Fan, Radio, TV]
[/java]

Hope it will help!!

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *