[英]Using Java 8 Streams, how to find the max for a given element in a HashMap
[英]How to find max key with some conditions in HashMap using Java 8 / Streams?
假设我有以下数据:
题 :
注意:我将此数据存储到 HashMap 中,名称为 orderBook,其中键为 orderId,值为 OrderModel(PairName、OrderType、Status、zscore)。
解决方案1:
int maxOrderId = 0 ;
getOrderBook().entrySet().stream()
.filter(e -> e.getValue().getPairName().equals("AB")
&& e.getValue().getCompletedStatus().equals("InProgress")
&& e.getValue().getOrderType().equals("Buy"))
.forEach(o -> {
if (maxOrderId < o.getKey()) {
maxOrderId = o.getKey();
}
});
double zscore = getOrderBook().get(maxOrderId).getzScore();
System.out.println("Order ID :"+ maxOrderId +", Zscore :"+zscore);
输出: Order ID : 5, Zscore : -2.5
我可以使用上面的代码找到 zscore,但我想一次性找到。
那么如何在一行中使用 Java 8 / 流找到最大 OrderId 的 zscore?
有没有比我的代码更好的方法?
您正在寻找的是max
方法:
Optional<Entry<Long,Order>> maxIdEntry = getOrderBook()
.entrySet()
.stream()
.filter(/* your filter logic */)
.max(Comparator.comparing(Entry::getKey));
这会产生一个 Optional,所以要么使用isPresent()
和get()
方法,要么使用ifPresent(Consumer<T> consumer)
方法来处理结果
您可以使用max()
使用Comparator
来获得最大的OrderId和使用map
的Optional
映射zScore
。
double zscore = getOrderBook()
.entrySet()
.stream()
.filter(e -> e.getValue().getPairName().equals("AB")
&& e.getValue().getCompletedStatus().equals("InProgress")
&& e.getValue().getOrderType().equals("Buy"))
.max(Comparator.comparing(Entry::getKey))
.map(e -> e.getValue().getzScore())
.orElse(0);
已经存在的答案非常好。 还有更多的方法:
使用能够保持键排序的TreeMap
怎么样? 只要钥匙是ex。 一个String
,你甚至不需要传递一个Comparator
。
// create a copy of HashMap as a TreeMap
NavigableMap<String, Order> navigableMap = new TreeMap<>(getOrderBook());
// remove unwanted entries (inverted condition)
navigableMap.entrySet().removeIf(e ->
!e.getValue().getPairName().equals("AB") ||
!e.getValue().getCompletedStatus().equals("InProgress") ||
!e.getValue().getOrderType().equals("Buy"));
// NavigableMap::lastEntry gets an entry with the highest key (by the comparator)
double zscore = sortedMap.lastEntry().getValue().getzScore();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.