Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sort Arraylist and return sorted list [duplicate]

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.

like image 710
Ceddy Muhoza Avatar asked Mar 01 '16 09:03

Ceddy Muhoza


2 Answers

You can do like this.

List<MyClass> unsortedList=...
List<MyClass> sortedList = unsortedList.stream()
            .sorted((MyClass o1, MyClass o2) -> o1.getStartDate().compareTo(o2.getStartDate()))
            .collect(Collectors.toList());

A more short form can be

List<MyClass> sortedList = unsortedList.stream()
                .sorted((o1,o2) -> o1.getStartDate().compareTo(o2.getStartDate()))
                .collect(Collectors.toList());
like image 124
Noor Nawaz Avatar answered Nov 07 '22 07:11

Noor Nawaz


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());
}
like image 36
SomeJavaGuy Avatar answered Nov 07 '22 08:11

SomeJavaGuy