gpt4 book ai didi

java - 流图以查找最新 key 的值

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:37:16 25 4
gpt4 key购买 nike

我有一个 Map<Element, Attributes>由以下(示例)类和枚举的实例组成,我想通过 stream() 获取最新键的值.最近的 key 可以由属性 creationTime 确定类(class) ElementMap 中的相应值只是一个 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并找到最近的 key ,然后我用它来简单地获取新代码行中的值。我想知道在单个 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仅当它包含至少一个键值对时才会被检查,这意味着总会有一个最新元素属性对,至少是一个。

最佳答案

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

关于java - 流图以查找最新 key 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54783273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com