gpt4 book ai didi

java - 使用流通过自定义比较器收集到 TreeSet

转载 作者:IT老高 更新时间:2023-10-28 11:46:51 26 4
gpt4 key购买 nike

在 Java 8 中工作,我有一个 TreeSet 定义如下:

private TreeSet<PositionReport> positionReports = 
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;
}
}

这很好用。

现在我想从 timestamp 早于某个值的 TreeSet positionReports 中删除条目。但我无法找出正确的 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))
)
);

但这不编译/似乎是方法引用的有效语法。

最佳答案

当您有一个适合您要满足的目标形状的方法(或构造函数)时,可以使用方法引用。在这种情况下,您不能使用方法引用,因为您要定位的形状是一个 Supplier,它不接受任何参数,但您拥有的是一个 TreeSet 构造函数,它确实需要一个参数,您需要指定该参数是什么。因此,您必须采用不太简洁的方法并使用 lambda 表达式:

TreeSet<Report> toTreeSet(Collection<Report> reports, long timestamp) {
return reports.stream().filter(report -> report.timestamp() >= timestamp).collect(
Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparingLong(Report::timestamp))
)
);
}

关于java - 使用流通过自定义比较器收集到 TreeSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21697349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com