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()?
Hãy thử 'Comparator comparing'. –
shmosel
@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! –
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