Frueps
Frueps

Reputation: 145

Java 8: Comparator returns stream of Object instead of specific type

my question is about the new java 8 collection streaming possibilities. I do have a sorted map with Date objects as keys. Now I have written the method below, which has to find the previous key in the keyset of a given Date. So iterating over the keyset in reverse order it would be the first date which is prior to the given search date. Here is my implementation:

private Date getPreviousKey(Date searchKey, Map<Date, SchluesselSum> timesAndSums) {
return timesAndSums.keySet().stream()
    .sorted(Comparator.<Date>reverseOrder())
    .filter(date -> date.before(searchKey))
    .findFirst()
    .orElse(null);
}

Now the problem is, that the call to .sorted(Comparator.reverserOrder()) returns a stream of java.lang.Object instead of Date and my compiler can't find .isLessOrEqual(...) in the .filter(...) call in the class Object.

How can I tell the .sorted method, or to be more precisely, the Comparator to return Date instead of Object?

Thank you in advance for any help!

Upvotes: 1

Views: 527

Answers (1)

assylias
assylias

Reputation: 328608

The problem seemed to be due to your custom Date class.

Note however that if your map also happens to be a NavigableMap (all SortedMaps in the JDK are navigable), you can call NavigableMap#lowerKey:

private Date getPreviousKey(Date searchKey, NavigableMap<Date, SchluesselSum> timesAndSums) {
  return timesAndSums.lowerKey(searchKey);
}

This will be more efficient (in terms of lines of code, readability and performance) than your current approach.

Upvotes: 4

Related Questions