1

I am using java.util.LinkedList

Is there any method that helps me with this?

user482594
  • 16,878
  • 21
  • 72
  • 108
  • 7
    `ArrayList` might be a better choice. Getting a random element from a `LinkedList` is O(N) cost (because you have to traverse from the first element to the chosen element). An `ArrayList` is O(1) to access a specific element. – Jeff Foster Jul 27 '11 at 10:02
  • Yeah.. my code now runs about 80% faster than before. Thanks!! – user482594 Jul 29 '11 at 19:28

5 Answers5

8
 int len = list.size(); 
 Random randomGenerator = new Random();
 int randomInt = randomGenerator.nextInt(len);
Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83
  • 3
    This just gets the a random index. Use `list.get(randomInt)` to get the actual value (as all the other answers have stated). – dacwe Jul 27 '11 at 10:15
  • Agreed. The question was select a random element though, so I stopped there. Thanks for the clarification. – Scott C Wilson Jul 27 '11 at 10:18
4

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);
dacwe
  • 43,066
  • 12
  • 116
  • 140
3

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);
Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
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.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
0

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.

Landei
  • 54,104
  • 13
  • 100
  • 195