How to shuffle a Collection?

Viewed 102

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?

2 Answers

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?

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

Related