使用流将元素收集到具有自定义比较器的TreeSet中
使用流将元素收集到具有自定义比较器的TreeSet中
在Java 8中工作时,我定义了一个TreeSet
,如下所示:
private TreeSetpositionReports = new TreeSet<>(Comparator.comparingLong(PositionReport::getTimestamp));
PositionReport
是一个相当简单的类,定义如下:
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; } }
这个工作正常。
现在我想从TreeSet positionReports
中删除timestamp
早于某个值的条目。但是我无法找出正确的Java 8语法来表达这个想法。
这个尝试实际上可以编译,但是它给我一个具有未定义比较器的新TreeSet
:
positionReports = positionReports .stream() .filter(p -> p.timestamp >= oldestKept) .collect(Collectors.toCollection(TreeSet::new))
我要如何表达,我希望收集到一个具有比较器Comparator.comparingLong(PositionReport::getTimestamp)
的TreeSet
?
我原以为可以这样做:
positionReports = positionReports .stream() .filter(p -> p.timestamp >= oldestKept) .collect( Collectors.toCollection( TreeSet::TreeSet(Comparator.comparingLong(PositionReport::getTimestamp)) ) );
但是这段代码无法编译/似乎无效的方法引用语法。