Nicolai Stoianov
Nicolai Stoianov

Reputation: 31

Get random strings from a list

I have an ArrayList which is defined outside the main method, just inside the class StringRandomize:

 public static ArrayList<String> countries = new ArrayList<String>();

I also initialized a random object.

 Random obj = new Random();

Then I add some Strings to the list:

    StringRandomize.countries.add("USA");
    StringRandomize.countries.add("GB");
    StringRandomize.countries.add("Germany");
    StringRandomize.countries.add("Austria");
    StringRandomize.countries.add("Romania");
    StringRandomize.countries.add("Moldova");
    StringRandomize.countries.add("Ukraine");

How do I make those strings appear randomly? I need output like "Germany", "Moldova" and so on.
I need exactly the strings in the output, not their IDs. Thanks for your help.

Upvotes: 1

Views: 239

Answers (3)

Simply Me
Simply Me

Reputation: 1587

static void shuffleArray(string[] ar)
  {
    //set the seed for the random variable
    Random rnd = ThreadLocalRandom.current();
    //go from the last element to the first one.
    for (int i = ar.size()- 1; i > 0; i--)
    {
      //get a random number till the current position and simply swap elements
      int index = rnd.nextInt(i + 1);
      // Simple swap
      int a = ar[index];
      ar[index] = ar[i];
      ar[i] = a;
    }
  }

This way you shuffle the entire array and get the values in a random order but NO duplicate at all. Every single element changes position, so that no matter what element (position) you pick, you get a country from a random position. You can return the entire vector, the positions are random.

Upvotes: 1

heniv181
heniv181

Reputation: 108

I would use Collections.shuffle(countries) if you wanted a randomized List.

Else a new Random().nextInt(max) like Flavius described.

Upvotes: 1

fanton
fanton

Reputation: 720

You probably want to use something like:

countries.get(Math.abs(new Random().nextInt()) % countries.size());

Or, to avoid creating a new Random object every time, you could use the same one:

Random gen = new Random();
for (int i = 1; i < 10; i++) {
    System.out.println(countries.get(Math.abs(gen.nextInt()) % countries.size()));
}

Upvotes: 3

Related Questions