Johannes
Johannes

Reputation: 2121

Sorted view of a List

is it somehow possible to get a sorted List view of a List with the elements from the original List, modify the elements, for example set a property, but the original List should reflect the changes?

Background is I'm sorting two Lists, then for each equal element I'm setting a property (basically it's the intersection) but finally I need the unsorted List with the modified elements.

kind regards,
Johannes

Upvotes: 1

Views: 1016

Answers (3)

TotoroTotoro
TotoroTotoro

Reputation: 17622

Does it have to be a list? If you keep your elements in a TreeSet, they will always be sorted as you iterate through them, even after you add/remove the elements. Remember though that modifying an element already in the TreeSet may break the sort order. You can remove and add the element to the TreeSet to get around that.

If you have to use a list, you can use Collections.sort(List list) after adding or modifying an element. Of course, if you have to call it often, there will be a performance hit. If performance is a concern, you can just insert the new element (or move the modified one) to maintain the sorted order, which will be cheaper than sorting it: O(n) vs O(n*log(n))

Upvotes: 1

Mark Elliot
Mark Elliot

Reputation: 77044

Probably the simplest thing to do is add the elements to a new list, sort that list, and when you modify the elements, the original elements will still be modified...

List<?> origA;
List<?> origB;

List<?> newA = new ArrayList<?>(origA);
List<?> newB = new ArrayList<?>(origB);

Collections.sort(newA);
Collections.sort(newB);

// do mods

Upvotes: 1

Axel Gneiting
Axel Gneiting

Reputation: 5413

If the List holds references to objects (not primitive data types), then just copy the list, sort it and modify the elements.

Upvotes: 1

Related Questions