Results 1 to 4 of 4
  1. #1
    ankit1801 is offline Member
    Join Date
    Mar 2011
    Posts
    20
    Rep Power
    0

    Default extracting 5 random elements from an ArrayList

    i have an arraylist of 30 elements. i need to randomly extract any 5 elements from the list. i am using the Random function but i am not getting 5 different elements, the elements are getting repeated. how to get unique entries from the arraylist? please help :(

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Use a random object and use nextInt for the range 0-29, use that to index into the array list, then keep track if numbers previously generated and ignore the random number if it's been seen already.

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,785
    Rep Power
    7

    Default

    If allowed the simplest way is to use Collections.shuffle and poll the first 5 objects.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Or shuffle() the list and take the first 5 elements. (But note the shuffle is "in place" - ie it will alter the ordering of the list being shuffled - so you might want to copy the list first.)

Similar Threads

  1. Replies: 9
    Last Post: 03-02-2011, 11:52 PM
  2. Adding elements to an ArrayList
    By ArcherSam in forum Advanced Java
    Replies: 7
    Last Post: 01-28-2011, 03:05 PM
  3. Replies: 6
    Last Post: 10-03-2010, 08:25 AM
  4. Cannot swap elements in ArrayList
    By glchau in forum New To Java
    Replies: 4
    Last Post: 05-30-2010, 08:03 AM
  5. Help printing specific ArrayList elements
    By CirKuT in forum New To Java
    Replies: 5
    Last Post: 02-03-2009, 12:24 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •