java Java排序Arraylist并返回排序列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35719713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java sort Arraylist and return sorted list
提问by Ceddy Muhoza
Hello am trying to return a sorted Arraylist by date property like in this answer
您好,我正在尝试按日期属性返回排序的 Arraylist,如本答案中所示
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.
我的问题是如何返回一个排序的列表而不是返回一个 int ...... 我需要的只是一个方法,我将它传递给我的列表然后它返回一个排序的列表。
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.
提前致谢。
采纳答案by SomeJavaGuy
if you want the sorted List
to be separated from the original one, do it like this.
如果您希望排序List
与原始排序分开,请这样做。
/**
* @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.
如果您还想更改原始List
,只需在原始实例上调用它。
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());
}
回答by Noor Nawaz
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());