Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 426
More Than Five Avatar asked Feb 14 '26 03:02

More Than Five


1 Answers

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().

like image 137
davidxxx Avatar answered Feb 15 '26 15:02

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!