I'm trying to find a minimum key value in my map. I'm inserting an AtomicLong
in value portion of the map which is initialized to system time like so:
map.putIfAbsent(instr,new AtomicLong(System.currentTimeMillis()));
Then at a later stage, I want to know the minimum value, here's code snippet:
map.entrySet()
.stream()
.filter(key -> key.getKey().getSymbol() == this.symbol)
.min(Map.Entry.comparingByValue())
.get()
.getKey()
I get the following error:
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>>>>)
It was working fine until I changed V part in Map<K,V>
from Long
to AtomicLong
due to thread safety concerns. Please let me know how to implement this functionality with stream. Thanks in advance!
Michael :
Long is comparable to itself because it implements Comparable<Long>.\n\nAtomicLong is not comparable to itself because it doesn't implement Comparable<AtomicLong>.\n\nThis means you cannot use Map.Entry.comparingByValue which takes a Comparable.\n\nYou could try this instead:\n\n.min(Map.Entry.comparingByValue(Comparator.comparingLong(AtomicLong::get)))\n",
2017-11-21T18:57:11
kotslon :
Do you really need Map.Entry.comparingByValue()?\n\nYou can \"implement\" your (almost :)) own Comparator:\n\n.min( (x, y) -> Long.compare(x.getValue().get(), y.getValue().get()) )\n",
2017-11-21T19:19:51