Ishratur Rahman
Ishratur Rahman

Reputation: 43

Sort an Arraylist without modifying the original list

I am in a situation where I just need to sort an Arraylist of custom object on a class member field. I need that just for displaying some information to the user. I tried with comparator but it's modifying the actual List which I don't want. So for a work around, I did a deep copy of my Arraylist and sorted that cloned Arraylist. Is there an memory efficient way of doing that without making a duplicate Arraylist?

Upvotes: 1

Views: 2885

Answers (3)

Alex R
Alex R

Reputation: 3311

Well, you don't actually need to make a deep copy unless your Comparator is mutating your objects, which it shouldn't. The easiest way is therefore to make shallow copy:

ArrayList<String> original = new ArrayList<>();
ArrayList<String> copy = new ArrayList<>(original);
copy.sort(Comparator.naturalOrder());

Replace Comparator.naturalOrder() with your actual Comparator implementation. For example, if you are comparing a member field, you can use Comparator.comparing as an easy way to create your desired Comparator.

And to answer your question: No, it's not possible without an additional data structure because on the one hand you want to alter the order of the elements, i.e. sort them, and on the other hand you want them to stay in the same order.

Upvotes: 4

WJS
WJS

Reputation: 40044

You can use streams. Just stream the original list, sort the elements, and create a new list. But the Objects in the list must implement the Comparable interface or you will need to create a Comparator to control the sort.

List<Integer> newList =
                original.stream().sorted(Comparator.naturalOrder())
                        .collect(Collectors.toList());

Say you had a Student class and you wanted to sort a list of students by age. Assume that you had a getAge method you could do it like this.

List<Student> newList =
                listOfStudents.stream().sorted(Comparator.comparing(Student::getAge))
                        .collect(Collectors.toList());

Neither of the above methods alter the original list.

Upvotes: 0

Anas Altarazi
Anas Altarazi

Reputation: 117

as I understood you wanna print your arraylist sorted without change its original sort. if that what you need you can make a temp arraylist or just an array and save sorted items in it then print them finally delete it (in java if you declared a local scope variable it will be deleted when the program leave its scope)

Upvotes: 0

Related Questions