kinx
kinx

Reputation: 493

How to shuffle a Collection?

I know about Collections.shuffle(), however it requires a List. I'd like to shuffle a Collection instead.

Collection<Town> towns = getAllTowns();

What would be the best way to do this?

Upvotes: 2

Views: 276

Answers (2)

robymus
robymus

Reputation: 71

It's not really possible - the Collection abstraction does not define an order, for example a set is Collection, and ordering is not defined on sets, thus shuffling them doesn't make sense.

You should convert your Collection to a list (if it is not a list already) and then shuffle it. See also: How to convert a Collection to List?

Upvotes: 4

j1mbl3s
j1mbl3s

Reputation: 1028

Collections can't necessarily be reordered, for example a Set. Therefore, you cannot shuffle an arbitrary Collection.

Upvotes: 2

Related Questions