Tuna Tuna - 4 months ago 9
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> {
@Override
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

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.add(0); 
    list.add(1);
    list.add(23);
    list.add(50);
    list.add(3);
    list.add(20);
    list.add(17);

    list.sort(new CustomComparator());
}