2016-07-27 101 views
1

我想根據三個條件對用戶列表進行排序。 所以我必須創建自定義比較排序列表,但它不工作,因爲我想使用自定義比較器不工作的排序列表

public class CustomComparator implements Comparator { 
    List<Integer> user1Time = new ArrayList<>(); 
    List<Integer> user2Time = new ArrayList<>(); 
    int user1Count, user2Count; 
    ParseUser user1, user2; 
    Date user1Date, user2Date; 
    boolean user1Short, user2Short; 
    private String TAG="CustomComparator"; 

    @Override 
    public int compare(Object lhs, Object rhs) { 
     user1 = (ParseUser) lhs; 
     user2 = (ParseUser) rhs; 


     user1Time = user1.getList("timeAvailable"); 
     user2Time = user2.getList("timeAvailable"); 


     //To compare Available time of both users with Searched Time 

     if(user1Time!=null){ 
      user1Time.retainAll(Utils.availableTime); 
      user1Count = user1Time.size(); 
     }else{ 
      user1Count=0; 
     } 

     if(user2Time!=null){ 
      user2Time.retainAll(Utils.availableTime); 
      user2Count = user2Time.size(); 
     }else{ 
      user2Count=0; 
     } 



     Log.d(TAG, "compare: "+user1.getString("name")+" "+user1Count); 
     Log.d(TAG, "compare: "+user2.getString("name")+" "+user2Count); 



     //To compare lastSeen of both the users 
     user1Date = user1.getDate("lastSeen"); 
     user2Date = user2.getDate("lastSeen"); 


     //To compare shortNotice avilablity of both the user 
     user1Short = user1.getBoolean("shortNotice"); 
     user2Short = user2.getBoolean("shortNotice"); 

     if(user2Time!= null && user2Time!= null && user1Date!= null && user2Date!= null){ 
      if (user1Count>user2Count){ 
       if(user1Short){ 
        if(user1Date.compareTo(user2Date)>0){ 
         return -1; 
        }else { 
         return -1; 
        } 
       }else if (user1Date.compareTo(user2Date)>0){ 
        return -1; 
       }else if (user2Date.compareTo(user1Date)>0){ 
        return 1; 
       } 
      }else if(user2Short){ 
       if(user2Date.compareTo(user1Date)>0){ 
        return 1; 
       }else { 
        return -1; 
       } 
      }else if (user2Date.compareTo(user1Date)>0){ 
       return 1; 
      }else if (user1Date.compareTo(user2Date)>0){ 
       return -1; 
      } 
     } 
      return 0; 
    } 
} 

,但它不是正確

我想排序中的整數,布爾三種方式陣列和日期 如清單工作你可以在我的代碼中看到。

+2

'但它工作不正常'定義不正常工作。請包括一個[MCVE](http://stackoverflow.com/help/mcve) – SomeJavaGuy

+0

使用'thenComparing' –

+2

你是什麼意思的「不工作」?你能更精細一點嗎? –

回答

0

你可以做這樣的事情:

class Data { 
int A; 
int B; 
int C; 

public int getA() { 
    return A; 
} 

public void setA(int a) { 
    A = a; 
} 

public int getB() { 
    return B; 
} 

public void setB(int b) { 
    B = b; 
} 

public int getC() { 
    return C; 
} 

public void setC(int c) { 
    C = c; 
} 
} 

class Sorter { 
public void sort(List<Data> dataList){ 
    Collections.sort(dataList, 
      Comparator.comparingInt(Data::getA) 
      .thenComparingInt(Data::getB) 
      .thenComparingInt(data->data.C) 
    ); 
} 
} 

這裏我只用comparingInt但是你可以用任何一種比較去做。

相關問題