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

Differences between list.sublist() and stream.limit()

I have two version of code which truncate an existing list:

version 1:

List<String> myList = User.getAllNames();
myList = myList.stream().sorted(sortByName).limit(5).collect(Collectors.toList());

version 2:

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

List<String> myList = User.getAllNames();
myList.sort(sortByName);
myList = myList.subList(0, 5 - 1);

Both versions truncate myList. As version 2 uses only subList which is baked by its origin list, I’m in doubt if version 2 also removes the clipped elements totally from the java heap (after garbage collection) like version 1 does.

Are there any differences between the two versions?

>Solution :

I’m in doubt if version 2 also removes the clipped elements totally from the java heap (after garbage collection)

Assuming no other objects have a reference to the clipped elements, they will be eligible for garbage collection in the case of version 1.

In the case of version 2, since the sublist produced is a "view" of the original list, the sublist needs to keep a reference to the original list, which contains all the clipped elements. Therefore, those clipped elements will not be eligible for garbage collection.

That said, this will probably not matter unless your lists have a lot of elements.

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