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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay