2016-03-01 38 views
-3

你好我试图在这个answerJava的排序ArrayList和返回排序列表

public class CustomComparator implements Comparator<MyObject> { 
@Override 
public int compare(MyObject o1, MyObject o2) { 
    return o1.getStartDate().compareTo(o2.getStartDate()); 
} 
} 

我的问题返回日期属性排序的ArrayList一样是我怎么可以返回一个排序列表,而不是返回一个int ... 我需要的仅仅是我通过它我的列表的方法则返回一个排序列表。

在我来说,我在列表项目很多,我不知道是否有可能比较所有的项目和他们相应的排序。

在此先感谢。

+3

Collections.sort(yourList,新CustomComparator()) – Eran

+1

喜@Eran可以请你发布一些例子,由于 – Tuna

+0

所以你读的答案,但在问题还没看一次?它向你展示了如何使用这个'CustomComparator'。 – Tom

回答

2

,如果你想排序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; 
} 

如果你也想改变原有的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()); 
} 
1

实现Comaparator接口后,你必须调用

 // sort the list 
     Collections.sort(list); 

方法对列表进行排序。 参见实施例herehere

1

你可以这样做。

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

更短的形式可以是

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