我有一个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
a来获得一个值,例如Map
stream()
Attributes latestValue = results.keySet().stream()
.max(Element::compareTo)
// what can I use here?
.somehowAccessTheValueOfMaxKey()
.get()
?
附加信息
我不需要像 之类的默认值null
,因为Map
只有在它包含至少一个键值对时才会检查它,这意味着总会有一个最近的元素-属性对,至少是一个。