Làm việc trong Java 8, tôi có một TreeSetđịnh nghĩa như sau:
private TreeSet<PositionReport> positionReports =
new TreeSet<>(Comparator.comparingLong(PositionReport::getTimestamp));
PositionReport là một lớp khá đơn giản được định nghĩa như thế này:
public static final class PositionReport implements Cloneable {
private final long timestamp;
private final Position position;
public static PositionReport create(long timestamp, Position position) {
return new PositionReport(timestamp, position);
}
private PositionReport(long timestamp, Position position) {
this.timestamp = timestamp;
this.position = position;
}
public long getTimestamp() {
return timestamp;
}
public Position getPosition() {
return position;
}
}
Điều này hoạt động tốt.
Bây giờ tôi muốn loại bỏ đi từ TreeSet positionReportsnơi timestampcũ hơn một số giá trị. Nhưng tôi không thể tìm ra cú pháp Java 8 chính xác để diễn đạt điều này.
Nỗ lực này thực sự biên dịch, nhưng mang lại cho tôi một cái mới TreeSetvới bộ so sánh không xác định:
positionReports = positionReports
.stream()
.filter(p -> p.timestamp >= oldestKept)
.collect(Collectors.toCollection(TreeSet::new))
Làm cách nào để diễn đạt, mà tôi muốn thu thập vào một TreeSetbộ so sánh như thế Comparator.comparingLong(PositionReport::getTimestamp)nào?
Tôi sẽ nghĩ một cái gì đó như
positionReports = positionReports
.stream()
.filter(p -> p.timestamp >= oldestKept)
.collect(
Collectors.toCollection(
TreeSet::TreeSet(Comparator.comparingLong(PositionReport::getTimestamp))
)
);
Nhưng điều này không biên dịch / dường như là cú pháp hợp lệ cho các tham chiếu phương thức.