0

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.

Jack
  • 1,339
  • 1
  • 12
  • 31
  • 1
    Is speed really a problem? Does it really slow you down _that much_ if you used a list? Also, your `Iterable` is unmodifiable, so it can't be shuffled in its current state anyway. – Sweeper Sep 03 '19 at 07:50
  • This may helps you (look at answers) https://stackoverflow.com/questions/3887262/randomly-iterate-over-arraylistinteger-in-java – Jean-Baptiste Yunès Sep 03 '19 at 07:50
  • You should consider using streams for what you're trying to do, not for performance reasons, but because they tend to play nicer with Collections. Iterable interface is a little awkward with the new streams and can be a pain to convert to/from. – Neil Sep 03 '19 at 08:00
  • if the Iterable is 10 million objects, I am sure it will affect the speed if i have to convert it into a list first. – Jack Sep 03 '19 at 08:05

1 Answers1

2

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • No, I ask this question mainly because such iterable can contain millions of objects, which is not tiny. – Jack Sep 03 '19 at 08:39
  • @Jack if the Iterable has millions of objects, you have a design problem. Besides, you don't have 10 million agents, so in **your** case there's no performance issues. There's no use in trying to optimize for imaginary situations. – Kayaman Sep 03 '19 at 08:50
  • I am modelling a nation wide parcel delivery network with over 20 million parcels (objects) per day. The size is actually huge. – Jack Sep 03 '19 at 08:57
  • @Jack that's the kind of important information you put in your question. So how are your `Iterable`s born? Are you generating elements dynamically or is there a backing collection or are you fetching them from the database? You might want to profile the application to see how much it really would affect performance if you collect them to a list. If you don't measure performance, it's only guesses and opinions (which are usually completely baseless). – Kayaman Sep 03 '19 at 09:02