Tuna Tuna - 1 year ago 65
Java Question

Java sort Arraylist and return sorted list

Hello am trying to return a sorted Arraylist by date property like in this answer

public class CustomComparator implements Comparator<MyObject> {
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());

My question is how can i return a sorted list instead of returning an int...
What i need is just a method i pass it my list then it returns a sorted list.

In my case i have many items in list, i dont know whether it's possible to compare all items and sort them accordingly.

Thanks in advance.

Answer Source

if you want the sorted List to be separated from the original one, do it like this.

 * @param input The unsorted list
 * @return a new List with the sorted elements
public static List<Integer> returnSortedList(List<Integer> input) {
    List<Integer> sortedList = new ArrayList<>(input);
    sortedList.sort(new CustomComparator());
    return sortedList;

If you also want to change the original List, simply invoke it on the original instance.

public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<>();

    list.sort(new CustomComparator());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download