You can’t sort Immutable Java Lists?

TheCodeAlchemist - Apr 23 '23 - - Dev Community

Follow me on YouTube for more content https://www.youtube.com/@therealdumbprogrammer/playlists

I was working on a sorting demo using Comparable and Comparator when I first noticed this.

So, if you create a new List by calling List.of(…) which returns an immutable list then you can’t sort this list in a straightforward manner.

Suppose, we have a list of integers.

List<Integer> nums = List.of(1, 4, 2, 3);
Enter fullscreen mode Exit fullscreen mode

And, if we try sorting this list via Collections.sort(..) or List.sort(..) then it throws an UnsupportedOperationExcecption.

nums.sort(null);
//OR
Collections.sort(nums);

----------------------------------
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
 at java.base/java.util.ImmutableCollections$AbstractImmutableList.sort(ImmutableCollections.java:261)
 at java.base/java.util.Collections.sort(Collections.java:145)
 at SortingDemo.main(SortingDemo.java:13)
Enter fullscreen mode Exit fullscreen mode

So, how can we sort such list. Well, streams can do that.

List<Integer> sortedNums = nums.stream()
                                .sorted()
                                .collect(Collectors.toList());
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player