2016-03-27 209 views
3

我需要對點列表進行排序。首先,我需要比較x值,然後如果x值相等,則爲y值。所以,我想我會用thenComparing方法:比較比較Int

Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y); 

但我不斷收到消息:不兼容類型:比較<對象>不能轉換到比較<點>。

我還有其他方法可以進行這種比較,它可以工作,但我不明白我在這裏做錯了什麼。

+0

也許你需要通過書寫(點)將它投射到一個點上。雖然不確定。 – Gendarme

回答

6

此代碼的工作:

Comparator<Point> cmp = Comparator.<Point> comparingInt(p -> p.x) 
            .thenComparingInt(p -> p.y); 

comparingInt,其中明確宣佈的p類型的前只增加<Point>拉姆達。這是必要的,因爲由於方法鏈,Java無法推斷出類型。

參見Generic type inference not working with method chaining?


這裏是另一替代:

Comparator<Point> cmp = Comparator.comparingDouble(Point::getX) 
            .thenComparingDouble(Point::getY); 

這裏,類型可以沒有任何問題地推斷。但是,您需要使用雙重比較,因爲getXgetY會返回雙倍值。我個人更喜歡這種方法。

2

嘗試改變:

Comparator<Point> cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y); 

Comparator<Point> cmp = Comparator.comparingInt((Point p) -> p.x).thenComparingInt((Point p) -> p.y); 
+0

是的,我做了測試,它工作得很好.. –