Jack
Jack

Reputation: 1437

Directly shuffle iterable in Java

Is there a way to shuffle iterable directly without converting it to list in JAVA?

        Iterable<Object> all =  Iterables.unmodifiableIterable(
                Iterables.concat(boy_agents,girl_agents));
        Collections.shuffle(all);

above shuffle() requires a list as input. I dont want to do a looping to create a list considering the computing speed.

Upvotes: 0

Views: 502

Answers (1)

Kayaman
Kayaman

Reputation: 73568

Shuffling requires random access. Iterator is an abstraction over data that allows you to just iterate and retrieve values.

So no, there's no way to shuffle an Iterator. If it comes from a backing (random access) collection you could shuffle that before retrieving the iterator, or you can shuffle the results when you've gathered them. But in your example of concatenating two iterators there's no chance.

If you don't need "real" shuffling (e.g. first element can become last), you could do it in chunks by getting N elements into a List and shuffling that.

Upvotes: 2

Related Questions