gpt4 book ai didi

java - 使用 Java 8 流查找映射中的最小键

转载 作者:行者123 更新时间:2023-12-01 16:47:26 25 4
gpt4 key购买 nike

我正在尝试在 map 中找到最小键值。我正在插入 AtomicLong在 map 的值部分中,它被初始化为系统时间,如下所示:

map.putIfAbsent(instr,new AtomicLong(System.currentTimeMillis())); 

然后在稍后阶段,我想知道最小值,这里是代码片段:

map.entrySet()
.stream()
.filter(key -> key.getKey().getSymbol() == this.symbol)
.min(Map.Entry.comparingByValue())
.get()
.getKey()

我收到以下错误:

The method min(Comparator<? super Map.Entry<Instrument,AtomicLong>>) in the type
Stream<Map.Entry<Instrument,AtomicLong>> is not applicable for the arguments
(Comparator<Map.Entry<Object,Comparable<? super Comparable<? super V>>>>)

它工作得很好,直到我改变了 Map<K,V> 中的 V 部分。来自LongAtomicLong由于线程安全问题。请让我知道如何使用流来实现此功能。提前致谢!

最佳答案

Long 与自身相当,因为它实现了 Comparable<Long> .

AtomicLong 与自身无法比较,因为它没有实现 Comparable<AtomicLong> .

这意味着您不能使用 Map.Entry.comparingByValue 这需要 Comparable .

你可以尝试这个:

.min(Map.Entry.comparingByValue(Comparator.comparingLong(AtomicL‌​ong::get)))

关于java - 使用 Java 8 流查找映射中的最小键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47420537/

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