javafilterjava-streamkeyset

Stream map in order to find value of latest key


I have a Map<Element, Attributes> consisting of instances of the following (example) class and enum, where I want to get the value of the most recent key via stream(). The most recent key can be determined by the property creationTime of the class Element and the corresponding value in the Map is just an enum 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 not that an Element implements Comparable<Element> just using the built-in comparison of LocalDateTime.

public enum Attributes {

    DONE,
    FIRST_REGISTRATION,
    SUBSEQUENT_REGISTRATION
}

My current approach is just able to filter the keySet and find the most recent key, which I then use to simply get the value in a new line of code. I was wondering if it is possible in a single stream().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);

Can we get a value by filtering the keySet of a Map in a single stream() statement like

Attributes latestValue = results.keySet().stream()
                .max(Element::compareTo)
                // what can I use here?
                .somehowAccessTheValueOfMaxKey()
                .get()

?

Additional information I do not need a default value like null, because the Map will only be checked if it contains at least one key-value pair, which means there will always be a most recent element-attribute pair, a single one, at least.


Solution

  • Attributes latestValue = results.keySet().stream()
                .max(Element::compareTo)
                .map(results::get)
                .get()