DEV Community

TheCodeAlchemist
TheCodeAlchemist

Posted on

You can’t sort Immutable Java Lists?

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

Top comments (3)

Collapse
 
alexts1993 profile image
Alex Ci

You can't do a in place sort to sort a immutable list

Collapse
 
therealdumbprogrammer profile image
TheCodeAlchemist

Could you please elaborate a bit more? I'm assuming by in-place you mean applying alogs like selection, insertion or heapsort not something JDK in-built, right?

Collapse
 
alexts1993 profile image
Alex Ci

Sorry I made a mistake, I mean that we can't modify a immutable List only