Using streams to collect into TreeSet with custom comparator
Method references can be used when you have a method (or constructor) that fits the shape of the target you're trying to satisfy. You can't use a method reference in this case because the shape you're targeting is a Supplier
, which takes no arguments, but what you have is a TreeSet
constructor, which does take an argument, and you need to specify what that argument is. So you have to take the less concise approach and use a lambda expression:
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))
)
);
}
This is easy just use next code:
positionReports = positionReports
.stream()
.filter(p -> p.timestamp >= oldestKept)
.collect(
Collectors.toCollection(()->new TreeSet<>(Comparator.comparingLong(PositionReport::getTimestamp)
)));
You can just convert into a SortedSet at the end (provided that you don't mind the additional copy).
positionReports = positionReports
.stream()
.filter(p -> p.getTimeStamp() >= oldestKept)
.collect(Collectors.toSet());
return new TreeSet(positionReports);
There is a method on Collection for this without having to use streams: default boolean removeIf(Predicate<? super E> filter)
. See Javadoc.
So your code could just look like this:
positionReports.removeIf(p -> p.timestamp < oldestKept);