nus-cs2103-AY2223S2 / forum

12 stars 0 forks source link

Question about how to sort the ObservableList<T> based on the date property of T #296

Closed QQH0828 closed 1 year ago

QQH0828 commented 1 year ago

I have tried several ways to try to sort ObservableList based on the date property of T, but sometimes it is not working perfectly on the GUI, so I want to ask is there any simply way to implement it?

For example, if there is a birthday property on a person, I want to sort Observablelist based on the birthday, and the person with a later birthday will be shown in the first index position in the list.

BTW, I just want to make sure that we cannot make a copy of Observablelist that is initialized by final.

SPWwj commented 1 year ago

Try this: model.getFilteredPersonList().sort((p1, p2) -> p1.getBirthday().compareTo(p2.getBirthday()));

ryanchua00 commented 1 year ago

A SortedList, similar to FilteredList, can be used to wrap the Observablelist to sort by property.

Originally in ModelManager, FilteredList wraps ObservableList to allow for filtering. A SortedList can wrap the original ObservableList in similar way.

QQH0828 commented 1 year ago

What I did is that I straightaway sorted in that observabllelist, something like internalList.sort(Comparator.comparing(Person::getBirthday)); FXCollections.reverse(internaList); Hence, I can directly get the sorted list, and it is still observablelist. But sometimes it is not shown on the GUI list correctly. However, it is shown on the other component correctly, such as chart.

SPWwj commented 1 year ago

sometimes

It look like a state issue, since sometime is working correctly and involved multiple components. Maybe you could provide us your code snippet by pushing the code to a branch, it is helpfull if we know how you:

jiasheng59 commented 1 year ago

I don't think FilteredList is intended to update for sorted, but SortedList definitely supports update in UI once you set setComparator to the list.

QQH0828 commented 1 year ago

I solved this issue by using stream.limit.collect and convert back to the observablelist. Thanks for discussion.