java – 流映射以便查找最新密钥的值
发布时间:2020-12-15 04:50:15 所属栏目:Java 来源:网络整理
导读:我有一个Map Element,Attributes由以下(示例)类和枚举的实例组成,其中我想通过stream()获取最新键的值.最近的键可以由类Element的属性creationTime确定,Map中的相应值只是一个枚举值: import java.time.LocalDateTime;import java.time.format.DateTimeForm
|
我有一个Map< Element,Attributes>由以下(示例)类和枚举的实例组成,其中我想通过stream()获取最新键的值.最近的键可以由类Element的属性creationTime确定,Map中的相应值只是一个枚举值:
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不能实现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);
Attributes latestValue = results.keySet().stream()
.max(Element::compareTo)
// what can I use here?
.somehowAccessTheValueOfMaxKey()
.get()
? 附加信息 解决方法Attributes latestValue = results.keySet().stream()
.max(Element::compareTo)
.map(results::get)
.get()
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
