Java sort Arraylist and return sorted list
17,020
Solution 1
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());
}
Solution 2
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());
Author by
Ceddy Muhoza
Updated on June 09, 2022Comments
-
Ceddy Muhoza almost 2 years
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.
-
itachi over 2 yearsThis doesn't return a sorted list.
Collections.sort(List<T>)
sorts the supplied list in-place.