Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Random data out of a list.

  1. #1
    Junior Member
    Join Date
    Jun 2011
    Posts
    4
    My Mood
    Confused
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question Random data out of a list.

    Say for example i create an array in the form,
    how can I get an element of the list randomly for use, and then remove it from the list.

    //Array List...
    	  ArrayList<Integer> list = new ArrayList<Integer>();
    	//Data inside the list are the numbers from 0-9
    	  for(int i = 0; i < 10; i++)
    	    list.add(i);


  2. #2
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    660
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Random data out of a list.

    Just get a random number and remove the element at that index, as follows:
    		int rand = new Random().nextInt(list.size());
    		list.remove(rand);

    Another alternative would be to use Collections.shuffle(List<?> list) to shuffle your ArrayList and pick the first few from the ArrayList.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

Similar Threads

  1. Generation of random number using random class
    By JavaPF in forum Java SE API Tutorials
    Replies: 1
    Last Post: December 7th, 2011, 04:46 PM
  2. Replies: 2
    Last Post: June 15th, 2011, 03:49 PM
  3. Spreadsheet data - linked list or hashmap
    By j919 in forum Collections and Generics
    Replies: 2
    Last Post: February 19th, 2011, 05:04 PM
  4. saving list of data from JSP into java object
    By nrao in forum JavaServer Pages: JSP & JSTL
    Replies: 4
    Last Post: January 12th, 2011, 10:24 AM
  5. SpinnerListModel setList(List<?> list)
    By roy epperson in forum Collections and Generics
    Replies: 4
    Last Post: November 29th, 2010, 09:30 AM

Tags for this Thread