0

I used an EditText widget where the client can enter information, then I saved several entries in an ArrayList. Now I want to randomly select one of these entries from the ArrayList. How can I select one element from an ArrayList at random?

I have already tried these ways but it crashes when I run it .

String myrandomString = String.valueOf(rand.nextInt(options.size()));

//int myrandomString = rand.nextInt(options.toString().length());
  • 1
    It isn't clear what your problem is from your question. Please consider revising if you'd like a high quality / relevant answer. – AJ X. Apr 28 '18 at 23:54

2 Answers2

1

If I understood correctly, you already have an ArrayList<String> that contains previously entered strings and when a new string is entered by the user it is appended to this list. What you would like to do is to select a random string from this list. You can use the java.util.Random class to generate a random index from the list and return the word that is positioned on that index. For example, the code bellow will print a random member of the test list on every execution.

Random random = new Random();

List<String> test = Arrays.asList("Text1","Text2","Text3","Text4");
System.out.println(test.get(Math.abs(random.nextInt()) % test.size()));

EDIT

As stated in the comments, replacing the Math.abs(random.nextInt()) % test.size() with random.nextInt(test.size()) will make the code more readable and reduce the chances for generating a lot of duplicates (it will make the number distribution more uniform).

Dimitar Spasovski
  • 2,023
  • 9
  • 29
  • 45
  • 1
    The method call [`random.nextInt(test.size())`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-) also accomplishes this without needing the final `% test.size()` – President James K. Polk Apr 29 '18 at 17:59
  • Not only does it accomplish the same, it's even much better. The modulo operation greatly reduces the randomness of the returned numbers. – Björn Zurmaar Apr 29 '18 at 18:08
  • @BjörnZurmaar can you point me to some resources that explain why the modulo operator reduces the randomness in this case? – Dimitar Spasovski Apr 29 '18 at 21:37
  • 1
    It's not only in this case, it's a general effect when using this kind of random number generator. See Effective Java item 47 and e.g. this question: https://stackoverflow.com/questions/27779177/effective-java-item-47-know-and-use-your-libraries-flawed-random-integer-meth – Björn Zurmaar Apr 29 '18 at 21:41
  • Thank you for the info guys I will update the answer. – Dimitar Spasovski Apr 29 '18 at 22:15
0

Start by picking a random index within the arrayList size:

int randIdx = new Random().nextInt(arrayList.size());

Then get the String at that index

String randString = arrayList.get(randIdx);
Bentaye
  • 9,403
  • 5
  • 32
  • 45