Sefler
Sefler

Reputation: 2237

Java random collection

Is there a kind of Java collection that the order of my fetching is random? For example, I put integer 1, 2, 3 into the collection and when I try to print them all the result can be "1 2 3","3 2 1" or "1 3 2"?

Upvotes: 23

Views: 16317

Answers (4)

Tom Jefferys
Tom Jefferys

Reputation: 13310

Not that I'm aware of. You could always put the values in a list, and use Collections.shuffle to put the values into a random order.

Upvotes: 1

Bill the Lizard
Bill the Lizard

Reputation: 406025

Just shuffle the collection.

If the collection must stay in order you could access elements at random indices, but then you have to keep track of ones you've used before (maybe, it depends on your application), and this can be very inefficient. A better solution, if memory is no obstacle, would be to just make a copy and shuffle that.

Upvotes: 2

Silfverstrom
Silfverstrom

Reputation: 29348

If you just want a random sequence you could use Collections.shuffle

    List<Integer> list = new LinkedList();
    //Add elements to list
    Collections.shuffle(list);

Upvotes: 52

Jon Skeet
Jon Skeet

Reputation: 1503280

Take a normal collection and shuffle it, then iterate over it in a normal way.

You can use java.util.Collections.shuffle(List<T>) to do the shuffling.

Upvotes: 5

Related Questions