I am using java.util.LinkedList
Is there any method that helps me with this?
I am using java.util.LinkedList
Is there any method that helps me with this?
int len = list.size();
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(len);
If you only need one element you can use the Random class to generate a (pseudo) random value (as you wrote in your question):
E element = list.get(new Random().nextInt(list.size()));
Remember LinkedList.get(index)
is an O(n) operation, as noted in the comments it's better to use an ArrayList
for this purpose.
If you want to shuffle the whole array you can use the Collections api like this:
Collections.shuffle(list);
You can also shuffle the List
using Collections.shuffle
and pick the first element everytime though this might be a bit expensive computation wise. Just another trick you should be aware of. :-)
final List<String> lst = Arrays.asList("a", "b", "c");
Collections.shuffle(lst);
final String rndStr = lst.get(0);
Get the list length with size()
, create a random number between 0 and size-1 and use get(index)
to retrieve the element with that index.
If you really need just one element, go with dacwe's solution. If you need several values (e.g. when simulating a card game, bingo etc.) you can use java.util.Collections.shuffle(list);
, and call list.remove(0);
for every element you need.