Java: renvoyer un élément aléatoire d'une liste
Normalement, nous utilisons les méthodes suivantes pour générer un nombre aléatoire en Java.
1. ThreadLocalRandom (JDK 1.7)
//Generate number between 0-9 int index = ThreadLocalRandom.current().nextInt(10);
2. Aléatoire()
//Generate number between 0-9 Random random = new Random(); int index = random.nextInt(10);
3. Math.random()
//Generate number between 0-9 int index = (int)(Math.random()*10);
Note
1. Pour un seul thread, il n'y a pas beaucoup de différence de performances, choisissez simplement ce que vous voulez.
2. Pour plusieurs threads, il est recommandé d'utiliserThreadLocalRandom
. Random est thread-safe, mais si plusieurs threads utilisent la même instance de Random, cela entraîne une forte contention (plusieurs threads pour continuer à accéder à la même méthode de générateur «aléatoire») et il tue les performances. ThreadLocalRandom résout ce problème en générant une instance Random par thread.
Lisez ceciThreadLocalRandom JavaDoc.
Dans ce didacticiel, nous allons vous montrer comment utiliser les méthodes ci-dessus pour obtenir un élément aléatoire d'une liste.
1. ThreadLocalRandom
Exemple deThreadLocalRandom
pour obtenir un élément aléatoire à partir d'une ArrayList.
ThreadLocalRandomExample.java
package com.example; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public class ThreadLocalRandomExample { public static void main(String[] args) { Listlist = new ArrayList (); list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); ThreadLocalRandomExample obj = new ThreadLocalRandomExample(); for(int i = 0; i < 10; i++){ System.out.println(obj.getRandomList(list)); } } public int getRandomList(List list) { //0-4 int index = ThreadLocalRandom.current().nextInt(list.size()); System.out.println("\nIndex :" + index ); return list.get(index); } }
Production. Le résultat sera différent à chaque exécution du programme.
Index :2 30 Index :4 50 Index :4 50 Index :3 40 Index :4 50 Index :0 10 Index :2 30 Index :1 20 Index :2 30 Index :4 50
2. Ramdom ()
Exemple deRandom
pour obtenir un élément aléatoire à partir d'une ArrayList.
RandomExample.java
package com.example; import java.util.ArrayList; import java.util.List; import java.util.Random; public class RandomExample { private Random random = new Random(); public static void main(String[] args) { Listlist = new ArrayList (); list.add("Apple"); list.add("Boy"); list.add("Cat"); list.add("Dog"); list.add("Elephant"); RandomExample obj = new RandomExample(); for(int i = 0; i < 10; i++){ System.out.println(obj.getRandomList(list)); } } public String getRandomList(List list) { //0-4 int index = random.nextInt(list.size()); System.out.println("\nIndex :" + index ); return list.get(index); } }
Sortie
Index :3 Dog Index :1 Boy Index :2 Cat Index :2 Cat Index :4 Elephant Index :1 Boy Index :2 Cat Index :0 Apple Index :0 Apple Index :3 Dog
3. Math.random()
Exemple deMath.random()
pour obtenir un élément aléatoire à partir d'une ArrayList.
MathRandomExample.java
package com.example; import java.util.ArrayList; import java.util.List; public class MathRandomExample { public static void main(String[] args) { Listlist = new ArrayList (); list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); MathRandomExample obj = new MathRandomExample(); for(int i = 0; i < 10; i++){ System.out.println(obj.getRandomList(list)); } } public int getRandomList(List list) { //Math.random() = greater than or equal to 0.0 and less than 1 //0-4 int index = (int)(Math.random()*list.size()); System.out.println("\nIndex :" + index ); return list.get(index); } }