2016-03-01 72 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());