Java – stream mapping to find the value of the latest key
I have a map < < element, attributes >, which consists of the following (example) classes and instances of enumeration, in which I want to get the value of the latest key through stream() The nearest key can be determined by the attribute creationtime of the class element. The corresponding value in the map is only an enumeration value:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Element implements Comparable<Element> { String abbreviation; LocalDateTime creationTime; public Element(String abbreviation,LocalDateTime creationTime) { this.abbreviation = abbreviation; this.creationTime = creationTime; } public String getAbbreviation() { return abbreviation; } public void setAbbreviation(String abbreviation) { this.abbreviation = abbreviation; } public LocalDateTime getCreationTime() { return creationTime; } public void setCreationTime(LocalDateTime creationTime) { this.creationTime = creationTime; } /* * (non-Javadoc) * * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(Element otherElement) { return this.creationTime.compareTo(otherElement.getCreationTime()); } @Override public String toString() { return "[" + abbreviation + "," + creationTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + "]"; } }
Please note that element cannot implement comparable < element > only uses the built-in comparison of localdatetime
public enum Attributes { DONE,FIRST_REGISTRATION,SUBSEQUENT_REGISTRATION }
My current method is to filter the keyset and find the latest key, and then I use it to simply get the value in the new code line I want to know if it can be in a single stream () In the filter (...) statement:
Map<Element,Attributes> results = new TreeMap<>(); // filling the map with random elements and attributes Element latestKey = results.keySet().stream().max(Element::compareTo).get(); Attributes latestValue = results.get(latestKey);
Attributes latestValue = results.keySet().stream() .max(Element::compareTo) // what can I use here? .somehowAccessTheValueOfMaxKey() .get()
?
For additional information, I don't need a default value like null, because the map will be checked only when there is at least one key value pair, which means that there will be at least one latest element attribute pair and one is unique
Solution
Attributes latestValue = results.keySet().stream()
Attributes latestValue = results.keySet().stream() .max(Element::compareTo) .map(results::get) .get()