rewrite-migrate-java icon indicating copy to clipboard operation
rewrite-migrate-java copied to clipboard

Java 16+ : Replace .collect(Collectors.toList()) with Stream.toList()

Open yeikel opened this issue 3 years ago • 0 comments

I believe that this depends on official Java 16 support . I am logging it now so we remember to do it


jshell> var numbers = List.of("1","2","3","4","5")
numbers ==> [1, 2, 3, 4, 5]

jshell> numbers.stream().map(Integer::valueOf).collect(Collectors.toList())
$10 ==> [1, 2, 3, 4, 5]

With the updated default method toList() in the Stream interface, you can now write shorter, clearer code such as :



jshell> numbers.stream().map(Integer::valueOf).toList()
$11 ==> [1, 2, 3, 4, 5]

We should only do this for lists that are not added or sorted as toList() returns an immutable list

One difference is that Stream.toList() provides a List implementation that is immutable (type ImmutableCollections.ListN that cannot be added to or sorted) similar to that provided by List.of() and in contrast to the mutable (can be changed and sorted) ArrayList provided by Stream.collect(Collectors.toList()).

More examples: https://jsparrow.github.io/rules/replace-stream-collect-by-to-list.html#code-changes

See :

https://stackoverflow.com/questions/65969919/differences-of-java-16s-stream-tolist-and-stream-collectcollectors-tolist https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/stream/Stream.html#toList%28%29=

yeikel avatar Apr 04 '22 22:04 yeikel