我有一个 Map<Element, Attributes>
由以下(示例)类和枚举的实例组成,我想通过 stream()
获取最新键的值.最近的 key 可以由属性 creationTime
确定类(class) 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
并找到最近的 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 aMap
in a singlestream()
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/