Travaillant en Java 8, j'ai TreeSetdéfini comme ceci:
private TreeSet<PositionReport> positionReports =
new TreeSet<>(Comparator.comparingLong(PositionReport::getTimestamp));
PositionReport est une classe assez simple définie comme ceci:
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;
}
}
Cela fonctionne très bien.
Maintenant, je veux supprimer les entrées de TreeSet positionReportsoù timestampest plus ancienne qu'une certaine valeur. Mais je ne peux pas comprendre la syntaxe Java 8 correcte pour exprimer cela.
Cette tentative compile en fait, mais me donne un nouveau TreeSetavec un comparateur non défini:
positionReports = positionReports
.stream()
.filter(p -> p.timestamp >= oldestKept)
.collect(Collectors.toCollection(TreeSet::new))
Comment exprimer ce que je souhaite collecter dans un TreeSetavec un comparateur comme Comparator.comparingLong(PositionReport::getTimestamp)?
J'aurais pensé à quelque chose comme
positionReports = positionReports
.stream()
.filter(p -> p.timestamp >= oldestKept)
.collect(
Collectors.toCollection(
TreeSet::TreeSet(Comparator.comparingLong(PositionReport::getTimestamp))
)
);
Mais cela ne compile pas / ne semble pas être une syntaxe valide pour les références de méthode.