This illustration will show how to get a random element from an ArrayList
. Each snippet initializes an arraylist and populates seed data. Next a Random
object is created and nextInt
is called bound to size of the within the array. Using java 8, a range of numbers to loop over the list a series of times to show off the example.
Straight up Java
@Test
public void random_value_arraylist_java() {
List<String> randomList = new ArrayList<String>();
randomList.add("one");
randomList.add("two");
randomList.add("three");
Random random = new Random();
for (int x = 0; x < 5; x++) {
System.out
.println(randomList.get(random.nextInt(randomList.size())));
}
}
Output
one
three
three
one
one
Java 8
@Test
public void random_value_arraylist_java8() {
List<String> randomValue = new ArrayList<String>();
randomValue.add("one");
randomValue.add("two");
randomValue.add("three");
Random random = new Random();
IntStream.range(0, 5).forEach(
a -> System.out.println(randomValue.get(random
.nextInt(randomValue.size()))));
}
Output
one
three
three
two
one