3

我有一个Map<Element, Attributes>由以下(示例)类和枚举的实例组成,我想在其中通过stream(). 最近的键可以由creationTime类的属性确定Element,对应的值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);

我们可以通过在单个语句中过滤keySeta来获得一个值,例如Mapstream()

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

?

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

4

3 回答 3

5

您可以找到 maxEntry而不是 max 键:

Attributes latestValue =
    results.entrySet()
           .stream()
           .max(Comparator.comparing(Map.Entry::getKey))
           .map(Map.Entry::getValue)
           .get();
于 2019-02-20T09:52:57.080 回答
5
Attributes latestValue = results.keySet().stream()
            .max(Element::compareTo)
            .map(results::get)
            .get()
于 2019-02-20T09:57:19.920 回答
1

您还可以将Collectors.toMapwithTreeMap用作地图工厂

Attributes value = results.entrySet().stream()
       .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, TreeMap::new))
       .lastEntry().getValue();
于 2019-02-20T10:12:02.707 回答