使用Java8流在映射中查找最小密钥
我试图在地图中找到一个最小的键值。我在映射的值部分插入一个使用Java8流在映射中查找最小密钥,java,filtering,java-stream,Java,Filtering,Java Stream,我试图在地图中找到一个最小的键值。我在映射的值部分插入一个AtomicLong,初始化为系统时间,如下所示: map.putIfAbsent(instr,new AtomicLong(System.currentTimeMillis())); 然后在稍后阶段,我想知道最小值,下面是代码片段: map.entrySet() .stream() .filter(key -> key.getKey().getSymbol() == this.symbol) .min(Map
AtomicLong
,初始化为系统时间,如下所示:
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>>>>)
方法min(Comparator与自身相当,因为它实现了comparable
是不可比的,因为它没有实现可比,这需要可比的
您可以尝试以下方法:
.min(Map.Entry.comparingByValue(Comparator.comparingLong(AtomicLong::get)))
与自身可比,因为它实现了compariable
是不可比的,因为它没有实现可比,这需要可比的
您可以尝试以下方法:
.min(Map.Entry.comparingByValue(Comparator.comparingLong(AtomicLong::get)))
是否确实需要Map.Entry.comparingByValue()
您可以“实现”您(几乎:)自己的比较器
:
.min( (x, y) -> Long.compare(x.getValue().get(), y.getValue().get()) )
是否确实需要Map.Entry.comparingByValue()
您可以“实现”您(几乎:)自己的比较器
:
.min( (x, y) -> Long.compare(x.getValue().get(), y.getValue().get()) )
就像错误所说:Comparator就像错误所说:Comparator“出于线程安全考虑,我将Map
中的V
部分从Long
更改为AtomicLong
。”为什么?难道Long
不像AtomicLong
那样不可更改吗?@TimothyTruckleAtomicLong
不是不可更改的,所以Long
更不可更改。@Michael还有一个不更改的理由……”出于线程安全考虑,我将Map
中的V
部分从Long
更改为AtomicLong
。“为什么?Long
不是像AtomicLong
那样不可变吗?@TimothyTruckleAtomicLong
不是不可变的,所以Long
更不可变。@Michael还有一个不改变的理由……可能更简单:.min(Comparator.comparingLong(e->e.getValue().get())
甚至更复杂,可能:.min(Entry.comparingByValue(Comparator.comparingLong(AtomicLong::get)))
所有这些解决方案的问题在于,比较不是原子的。如果没有额外的锁,它就不可能是原子的。非常感谢@kotslon和您的建议,非常感谢!非常感谢@Enwired的建议,非常感谢!更简单的可能是:.min(Comparator.comparingLong(e->e.getValue()).get())
可能更复杂:.min(Entry.comparingByValue(Comparator.comparingLong(AtomicLong::get)))
所有这些解决方案的问题在于,比较不是原子性的。如果没有额外的锁,它就不可能是原子性的。非常感谢@kotslon,感谢你的建议,非常感谢!非常感谢@Enwired,感谢你的建议,非常感谢!你可以使用。@shmosel正确,但也许我们都应该解释一下这是关于我们所指的签名。你可以使用。@shmosel是正确的,但也许我们都应该明确我们所指的签名。