Hamlet has been sent away to England by his uncle/stepfather, Claudius, the king. However, he writes to Horatio to tell him that, having been only two days at sea, "a pirate of very warlike appointment" began to chase his ship (4.6.15-16). There was a fight, and during the skirmish, Hamlet boarded the pirates' ship. When the two ships separated shortly thereafter, he became trapped on the pirates' ship and became their prisoner. This episode may provide a clue as to Hamlet's mental state at this point in the play. Yes, running into random pirates seems like dumb luck, but Hamlet's willingness to board their ship and fight shows great bravery and valor. Further, his ability to negotiate a ride back to Denmark in safety with this "warlike" group shows us that his critical thinking skills are still up to snuff. He doesn't panic; instead, he works out how to parley his position into freedom. He tells Horatio, "I am to do a good turn for them." This makes it seem like, no matter how mad Hamlet acts, he still possesses the good sense that has always characterized him.
Hamlet is "captured" and rescued by pirates. It is really stretching believability at this point, but it was necessary to get Hamlet back.
If we go with Hamlet's belief in fate, it was meant to be.