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.
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());
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With