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?
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With