This is a great question because without some thoughtful consideration it may seem strange that a play that has been all about Hamlet and his thoughts and actions actually ends with the words of a minor character who has only been on stage during Act 4 and talked about three times. That said, however, it is perfectly logical that Shakespeare ends the play with the arrival of Fortinbras and that ultimately the kingdom of Denmark passes into his hands.
At the very start of the play Horatio reveals that Fortinbras is an ambitious young prince "of unimproved mettle, hot and full." He is on a mission to regain the lands that his father lost to King Hamlet in a battle years earlier. Fortinbras is so determined to accomplish his goals that he hires mercenaries to be his army and is planning boldly to attack Denmark when it would be perceived as vulnerable due to the recent death of King Hamlet and transition to the new king, Claudius.
Claudius, in a effort to avoid this conflict, negotiates with Fortinbras's uncle and secures a promise that Fortinbras will not attack Denmark. Instead, Fortinbras wants to secure passage through the country to attack Poland for a piece of land there. Later, Hamlet sees the young Prince on this journey. Hamlet is immediately struck by the fact that Fortinbras is willing to fight hard and lose men in order to regain a worthless piece of land because he is doing it in the name of honor. Hamlet can't help but be struck by the contrast to himself who also has all the right reasons in the world to act against Claudius, but just can't take the decisive action to gain his revenge.
When in Act 5 Hamlet learns from Laertes that he has been struck by the poisoned sword and he realizes that he will die, he also knows that with his death the kingdom will fall into chaos with no other royal family member to ascend the throne. With those thoughts he gives his one and only act as "king." He tells Horatio "I do prophesy the election lights / On Fortinbras. He has my dying voice." He is essentially handing the kingdom to Fortinbras. Because there are no other alternatives, Hamlet makes a good decision. Fortinbras recognizes the irony of this when he comments that "it is with sorrow that I embrace my fortune." His first act as king is to give Hamlet the funeral dignity he deserves and thus Fortinbras's presence provides a proper sense of closure to a play that ends in so many deaths.