2

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?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
kinx
  • 463
  • 5
  • 12
  • 31
  • 1
    A `Collection` does not necessarily have an order. e.g. _hash sets_ are collections, but has not order. If it's a collection that has no order, it does not make sense to "shuffle" it, does it? – Sweeper Jun 05 '21 at 03:56
  • 1
    Note, it's `Collections.shuffle()` not `Collection.shuffle()`, and as you already noted, it can be applied ONLY to something with an intrinsic ordering. In Java, the base for an ordered collection is `List<>`. – Jim Garrison Jun 05 '21 at 04:45

2 Answers2

4

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?

robymus
  • 71
  • 2
2

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

j1mbl3s
  • 994
  • 3
  • 16