How to Retrieve Random Item from List in Java


Here the next two examples will demonstrate how to randomly get items from a List in Java.

Source Code

1)

package com.beginner.examples;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomItemFromAList {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Random random=new Random();
		List al=new ArrayList();
		al.add("a");
		al.add("b");
		al.add("c");
		al.add("d");
		for(int i=0;i<4;i++)
		{
			System.out.println("Random access:"+al.get(random.nextInt(al.size())));
		}
	}

}

Output:

Random access:b
Random access:b
Random access:d
Random access:c

2)

package com.beginner.examples;

import java.util.ArrayList;
import java.util.List;


public class RandomItemFromAList2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
			ArrayList aList=new ArrayList();
			aList.add(1);
			aList.add(2);
			aList.add(3);
			aList.add(4);
			for(int i=0;i<4;i++)
			{
				System.out.println("Random access:"+randomList(aList));
			}
	}
	public static  T randomList(ArrayList al)
	{
		
		return  al.get((int)(Math.random()*al.size()));
	}

}

Output:

Random access:4
Random access:3
Random access:1
Random access:2

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments