how to get a random item from a list in java code example
Example 1: select a random element from a list java
Random randomizer = new Random();
String random = list.get(randomizer.nextInt(list.size()));
Example 2: random.choice in java
String[] available_cards = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Queen", "King", "Jack", "Ace"};
java.util.Random random = new java.util.Random();
int random_computer_card = random.nextInt(available_cards.length);
System.out.println(available_cards[random_computer_card]);
Example 3: how to get random element from list in java
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Hello
{
public static void main(String[] args)
{
List<String> l = new ArrayList<>();
l.add("Quote of the Day \r\nIf you find it in your heart to care for somebody else, you will have succeeded. \r\nReopen the program for another quote.");
l.add("Love Quote of the Day \r\nIf there's delight in love, 'Tis when I see that heart, which others bleed for, bleed for me. \r\nReopen the program for another quote.");
l.add("Art Quote of the Day \r\nArt is the stored honey of the human soul, gathered on wings of misery and travail. \r\nReopen the program for another quote.");
l.add("Nature Quote of the Day \r\nThe earth has received the embrace of the sun and we shall see the results of that love. \r\nReopen the program for another quote.");
l.add("Funny Quote Of the Day \r\nThe first condition of understanding a foreign country is to smell it. \r\nReopen the program for another quote.");
l.add("Quote of the Day \r\nAnger cannot be dishonest. \r\nReopen the program for another quote.");
l.add("Love Quote of the Day \r\nLove is when he gives you a piece of your soul, that you never knew was missing. \r\nReopen the program for another quote.");
l.add("Art Quote of the Day \r\nIt is only an auctioneer who can equally and impartially admire all schools of art. \r\nReopen the program for another quote.");
l.add("Nature Quote of the Day \r\nNature reserves the right to inflict upon her children the most terrifying jests. \r\nReopen the program for another quote.");
l.add("Funny Quote Of the Day \r\nMarriage is not just spiritual communion, it is also remembering to take out the trash. \r\nReopen the program for another quote.");
Hello obj = new Hello();
String inputValue = JOptionPane.showInputDialog("Please enter your name: ");
Random rand = new Random();
int randomIndex = rand.nextInt(l.size());
String randomElement = l.get(randomIndex);
JOptionPane.showMessageDialog(null, randomElement + "\r\n\r\nHave a nice day " + inputValue + "!");
}
}