Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If List is an abstract interface, how does Collectors.toList() work with streams?

I understand this will not work because List is an abstract interface:

List<Integer> l = new List<>();

and this is why I have been using typically ArrayList<>.

I’m curious why the following is valid in assignment of an object to List<String> l:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ArrayList<E> al = new ArrayList<>();
List<String> l = al.stream().collect(Collectors.toList());

It was my understanding objects couldn’t be created from interfaces, only when they have been implemented. Can anyone explain why second code snippet works and how I should be understanding this difference?

>Solution :

Collectors.toList() will return you some concrete List instance. Maybe an ArrayList, maybe something else. All the API is willing to guarantee is that it conforms to the List interface.

The Javadoc explicitly states:

There are no guarantees on the type, mutability, serializability, or
thread-safety of the List returned; if more control over the returned
List is required, use toCollection(Supplier).

You can check the specific type that is returned at runtime, but shouldn’t rely on it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading