1

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.

4 Answers 4

3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Or myArray.subList(0, 6)
3

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.

1 Comment

This method can have repeats, it does not pick 6 unique elements.
1
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

Comments

0

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.