Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list without mutating it

Tags:

java

sorting

I would like to sort a List of items in Java and have the sort return a new sorted List without mutating the original List. Is there a commonly used library that does this?

like image 299
Alex Spurling Avatar asked Jan 01 '23 23:01

Alex Spurling


2 Answers

If you are using Java 8 or higher, you can use the Stream API. See Sorting a list with stream.sorted() in Java for details.

For example:

List<String> sortedList = myList.stream().sorted().collect(Collectors.toList());
like image 183
Code-Apprentice Avatar answered Jan 04 '23 13:01

Code-Apprentice


This copies (by reference) the elements in the original list to the new list. Making changes like the ordering of one list won't affect the other.

List<String> originalList = new ArrayList<String>();
List<String> newList = new ArrayList(originalList);

Please note if you modify the objects that are in the list however, the changes will be reflected in both lists since objects are copied by reference.

like image 23
Rosa Mohammadi Avatar answered Jan 04 '23 13:01

Rosa Mohammadi