Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which toArray conversion pattern is best to use?

I had the following piece of code that IntelliJ suggested I should change:

String[] normalizedNames = rawToNormalized.values().stream().toArray(String[]::new);

into

String[] normalizedAliases = rawToNormalized.values().toArray(new String[0]);

Aleksey Shipilёv's post (https://shipilev.net/blog/2016/arrays-wisdom-ancients/) suggested:

toArray(new T[0]) seems faster, safer, and contractually cleaner, and therefore should be the default choice now."

Can someone please elaborate how exactly toArray(new String[0]) differs from toArray(String[]::new) by going from stream and using toArray without Collector.

Can toArray(new String[0]) still be used in the stream? Will it still be a more performant/better choice?

like image 276
QuirkyBit Avatar asked Nov 07 '22 12:11

QuirkyBit


1 Answers

I would follow intelliJ as one simple reason :

Why you trasform your list to stream to create an array. In the other side you can transform that list to an array directly.

Can someone please elaborate how exactly toArray(new String[0]) differs from toArray(String[]::new) and if toArray(new String[0]) still the more performant/better choice?

The idea behind the intelliJ warning is about using stream befor toArray and not the way of using toArray

like image 153
YCF_L Avatar answered Nov 12 '22 20:11

YCF_L