5

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?

Alex Spurling
  • 54,094
  • 23
  • 70
  • 76
  • 3
    All Java SE collection classes have a constructor that copies another collection. Using that, you can do `List sortedList = new ArrayList<>(unsortedList); sortedList.sort(null);` – VGR Aug 24 '18 at 21:10
  • 2
    1) Copy it, sort the copy, or 2) `stream()` it, sort the `Stream`. Perhaps 3) create a sorted _view_ - but that would have `O(lg n)` access times, so probably not useful. – Boris the Spider Aug 24 '18 at 21:10

2 Answers2

8

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());
Alex Spurling
  • 54,094
  • 23
  • 70
  • 76
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
2

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.

Elyas Hadizadeh
  • 3,289
  • 8
  • 40
  • 54