2017-02-09 66 views
8

Hãy nói rằng tôi có một lớp PairJava 8 Comparator so sánh không thực hiện chuỗi

public class Pair<P, Q> { 
    public P p; 
    public Q q; 


    public Pair(P p, Q q) { 
     this.p = p; 
     this.q = q; 
    } 

    public int firstValue() { 
     return ((Number)p).intValue(); 
    } 

    public int secondValue() { 
     return ((Number)q).intValue(); 
    } 
} 

Và tôi muốn sắp xếp nó, trước hết bởi giá trị đầu tiên, sau đó theo giá trị thứ hai. Bây giờ' nếu tôi làm

List<Pair<Integer, Integer>> pairList = new ArrayList<>(); 
pairList.add(new Pair<>(1, 5)); 
pairList.add(new Pair<>(2, 2)); 
pairList.add(new Pair<>(2, 22)); 
pairList.add(new Pair<>(1, 22)); 
pairList.sort(Comparator.comparing(Pair::firstValue)); 

Tất cả mọi thứ này hoạt động tốt và tốt, danh sách được sắp xếp theo giá trị đầu tiên của cặp, nhưng nếu tôi làm điều này

pairList.sort(Comparator.comparing(Pair::firstValue).thenComparing(Pair::secondValue)); 

Nó thất bại với lỗi

Error:(24, 38) java: incompatible types: cannot infer type-variable(s) T,U 
(argument mismatch; invalid method reference 
    method firstValue in class DataStructures.Pair<P,Q> cannot be applied to given types 
    required: no arguments 
    found: java.lang.Object 
    reason: actual and formal argument lists differ in length) 

Ok, do đó, nó có thể không thể suy ra các đối số, vì vậy nếu tôi làm điều này

pairList.sort(Comparator.<Integer, Integer>comparing(Pair::firstValue) 
              .thenComparing(Pair::secondValue)); 

Nó thất bại với lỗi

Error:(24, 39) java: invalid method reference 
non-static method firstValue() cannot be referenced from a static context 

Tại sao nó hoạt động để so sánh() và không để so sánh(). ThenComparing()?

+2

Hãy thử 'Comparator comparing'. – shmosel

+0

@shmosel wow đã hoạt động, bạn có nhớ thêm nó làm câu trả lời với lý do tại sao nó hoạt động không! Cảm ơn! –

+0

Tôi nghi ngờ bạn sẽ có ít vấn đề hơn nếu bạn sử dụng [Comparator.comparingInt] (https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#comparingInt-java.util.function .ToIntFunction-). – VGR

Trả lời

5

Lỗi này có vẻ liên quan đến thông số chung của Pair. Một cách giải quyết nó sử dụng một loại rõ ràng, như bạn đã cố gắng:

pairList.sort(Comparator.<Pair>comparingInt(Pair::firstValue).thenComparingInt(Pair::secondValue)); 
//      ^^^^^^ 

Lưu ý comparingInt() làm giảm số lượng các tham số bạn cần phải xác định và cải thiện hiệu suất bằng cách tránh boxing.

giải pháp khác là tham số tham chiếu loại:.

pairList.sort(Comparator.comparingInt(Pair<?,?>::firstValue).thenComparingInt(Pair::secondValue)); 
//          ^^^^^ 
3

Nó nên là:

pairList.sort(Comparator.<Pair, Integer>comparing(Pair::firstValue) 
             .thenComparing(Pair::secondValue)); 

tham số kiểu đầu tiên đề cập đến các loại đang được truyền cho sánh. Tham số loại thứ hai đề cập đến loại so sánh nên so sánh hiệu quả với.

Các vấn đề liên quan