2013-01-15 21 views
0

我有一個員工集合。每個員工都有一個ID。此ID號碼格式爲 -x> = 0> = x。我必須將Employees排序爲0 ... x -1 ....- x。我怎樣才能做到這一點??收集排序 - 正值,0,負值順序

List<Employee> empSort = new ArrayList(em.getEmployees()); 
Collections.sort(empSort, new Comparator<Employee>() { 
       @Override 
       public int compare(Employee p1, Employee p2) { 
        // WHAT LOGIC SHOULD I DO THERE TO HAVE THEM 
             SORTED AS 0...x -1....-x 
       } 
      }); 
+0

你希望所有的負數字出現在非負數之後,按照從負數到負數的順序排列?例如你想0 <10 <-1 <-10,即使10> -1和-1> -10 –

+0

@PeterLawrey是的,我希望它作爲0,1,2 ... 10,-1,-2,-3 ...- 10 – rr87

回答

2

給它一些思想對晚餐和我喜歡這個更好。

int sign1 = (p1 >= 0) ? 1 : -1; 
int sign2 = (p2 >= 0) ? 1 : -1; 

int result = Integer.compare(sign2, sign1); 

if(result == 0){ 
    // same sign 
    result = sign1 * Integer.compare(p1, p2); 
} 
return result; 

輸出仍然是:

[0, 0, 0, 1, 3, 5, -1, -2] 
+0

可以說我希望永久類型的員工永遠是第一個顯示的,不管他們有什麼ID。我怎樣才能做到這一點???其他類型的emplyees將遵循這個排序順序 – rr87

+0

如何:'int permanent1 = p1.isPermanent()? -1:1; int permanent2 = p2.isPermanent()? -1:1; int result = Integer.compare(permanent1,permanent2); if(result == 0){[... the rest]}返回結果;' – flup

+0

或者你可以利用這個事實,即Collections.sort()是一個穩定的排序,首先做這種排序,然後再做第二排序它只比較isPermanent()。它會留下ID排序。 – flup

1

難道你不能執行三個測試嗎?

非負面出現在負面之前。 return如果只有一個是負數。

如果兩者均爲負值,則 值越大,值越小。

如果兩者均爲非負值,則 值越小,值越大。

+3

+1:這是在編程之前使用鉛筆和紙張的好例子。 –

0

比較返回一個負整數,零或一個正整數,因爲第一個參數小於,等於或大於第二個參數。

if(p1.id * p2.id < 0) { 
    // opposite sign 
    // if p1 is negative, p2 is positive, p1 is greater than p2 
    // otherwise p1 is positive, p2 is negative, p1 is less than p2 
    return -p1.id; 
} 
if(p1.id > 0 && p2.id > 0 || p1.id + p2.id >= 0) { 
    // both positive, normal ordering or a zero and a positive number, also normal ordering 
    return p1.id - p2.id; 
} 
if(p1.id <0 && p2.id < 0){ 
    // both negative, inverse ordering 
    return p2.id - p1.id; 
} 
// zero and a negative number, zero comes first 
if(p1.id == 0) { 
    return -1; 
} 
return 1; 

[0,0,0,1,3,5,-1,-2]

0

它是不起眼的,但你可以做

Integer.compare(x >= 0 ? x + Integer.MIN_VALUE : ~x, y >= 0 ? y + Integer.MIN_VALUE); 

或更模糊的

Integer.compare(x^(-1 << ~(x >> -1)), y^(-1 << ~(y >> -1))) 

注:相同的公式會爲工作long s;)

這地圖[0,Integer.MAX_VALUE的]到[Integer.MIN_VALUE的,-1]和[Integer.MIN_VALUE的,-1]被翻轉到[0,是Integer.MAX_VALUE]