John Smith
John Smith

Reputation: 75

Randomize a subset of Items in an ArrayList

I want to create a quiz, I have 20 items in an ArrayList that is in MainActivity. How do i pick 6 random items from the ArrayList each time i click to Open DetailActivity, passing the random items?

P.S I know how to navigate between activities and passing data through Intents, I just want to know how get 6 random items from the ArrayList.

Upvotes: 1

Views: 455

Answers (4)

Jay Smith
Jay Smith

Reputation: 2480

To generate number between 0 and list.size() use:

int index = ThreadLocalRandom.current().nextInt(list.size());

Having random index you can get element from list:

list.get(index);

Upvotes: 0

user8201141
user8201141

Reputation:

You can shuffle the ArrayList using Collections.shuffle:

long seed = System.nanoTime();
Collections.shuffle(myArray, new Random(seed));

In order to get 6 items, you can use myArray.subList(0, 6).

Upvotes: 3

davidxxx
davidxxx

Reputation: 131324

Use a Random object :

Random random = new Random();
myList.get(random.nextInt(myList.size())));

Or you can also Collections.shuffle(myList); that under the hood also uses a Random but that should have a slight overhead as it iterates on all elements of the list.

In your case, as you need to retrieve probably 6 distinct elements, you should rather use Collections.shuffle(myList); as it will allow to retrieve 6 distinct elements with myList.subList(0,6);.
By iterating 6 times with myList.get(random.nextInt(myList.size())));, you could have multiple times the same element.

Upvotes: 3

Ebrahim Poursadeqi
Ebrahim Poursadeqi

Reputation: 1816

ArrayList<Integer>  list = new ArrayList<Integer>();
lista.add(1);
lista.add(2);
lista.add(1);
lista.add(3);
lista.add(4);
lista.add(5);
lista.add(6);
.
.
.

Collections.shuffle(list);

now you can get index 0 to 5 and its randomized

Upvotes: 1

Related Questions