More Than Five
More Than Five

Reputation: 10419

Streams versus collections

I have a list of players and want to get the player with the min rating. I could do:

Player player1 = Collections.min(players,Comparator.comparing(Player::getRating));

Or I could do:

Player player2 = players.stream().min(Comparator.comparing(Player::getRating)).get();

What's better in terms of performance or anything else?

Upvotes: 2

Views: 122

Answers (3)

Eugene
Eugene

Reputation: 120858

Well, if the incoming source is already sorted, the Stream implementation could potentially just return the first (or last) entry from that source, without traversing the entire Collection unlike Collections.min. For your example that seems way too complicated to do probably, but for a simpler one things would be easier may be.

This is not done at the moment, but could be implemented in the future, as such I could favor the stream one probably.

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56433

Given your question is "What's better in terms of performance or anything else?" @davidxxx and @Eugene have already elaborated on some interesting points, here's another one:

Another reason to favour the stream variant is that the call upon min returns an Optional<T> which itself is descriptive enough and also enables the user to decide what to do in the "no value" case whereas the Collections.min would simply throw an exception if the collection is empty, which may as well be what the user wants but it's something to take into consideration. My personal preference would be the stream version simply because it provides you more options in terms of what to do in the "no value" case.

That said if you don't need those additional options simply because there will always be a min value or an exception is meaningful enough then I'd go with the first approach.

Ultimately, what option you decide to proceed with should not depend on performance because there's not a huge difference in between them unless otherwise, you believe you can leverage the parallel stream API.

Rather, in this specific case, I'd suggest you take into consideration what I've mentioned above and go with the more readable/comfortable approach to you and/or your colleagues.

Upvotes: 3

davidxxx
davidxxx

Reputation: 131346

It should not make a great difference.
We could argue that the stream way could take advantage of the parallel stream option while Collections.min() could not.
And in both cases you present, the boxing may have a cost with a big list. So you should favor comparingInt()/comparingDouble()/comparingLong() to comparing().

Upvotes: 3

Related Questions