流图以查找最新密钥的值

Stream map in order to find value of latest key

我有一个 Map<Element, Attributes> 由以下(示例)class 和枚举的实例组成,我想通过 stream() 获取最新键的值。 class Element中的属性 creationTime可以确定最近的key,而Map中对应的值就是一个enum值:

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) + "]";
    }
}

请注意 Element implements Comparable<Element> 只是使用 LocalDateTime.

的内置比较
public enum Attributes {

    DONE,
    FIRST_REGISTRATION,
    SUBSEQUENT_REGISTRATION
}

我目前的方法只能过滤 keySet 并找到最近的密钥,然后我用它来简单地在新的代码行中获取值。我想知道是否可以在单个 stream().filter(...) 语句中实现:

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()

?

附加信息 我不需要像 null 这样的默认值,因为 Map 只有在包含至少一个键值对时才会被检查,这意味着总会有一个 最近的 元素-属性对,至少一个。

您可以找到最大值 Entry 而不是最大值键:

Attributes latestValue =
    results.entrySet()
           .stream()
           .max(Comparator.comparing(Map.Entry::getKey))
           .map(Map.Entry::getValue)
           .get();
Attributes latestValue = results.keySet().stream()
            .max(Element::compareTo)
            .map(results::get)
            .get()

您还可以将 Collectors.toMapTreeMap 一起用作地图工厂

Attributes value = results.entrySet().stream()
       .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, TreeMap::new))
       .lastEntry().getValue();