最新のキーの値を見つけるためにストリームマップ

deHaar:

私が持っている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);

私たちは、フィルタリングすることで値を得ることができるkeySetのをMap単一にstream()文のよう

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

追加情報は、私のようなデフォルト値を必要としないnullので、Mapのみチェックされます、それは常に存在します、少なくとも1つのキーと値のペア、含まれている場合は、最新少なくとも、要素と属性のペア、単一のものを。

スーツ:
Attributes latestValue = results.keySet().stream()
            .max(Element::compareTo)
            .map(results::get)
            .get()

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=196359&siteId=1