Home:ALL Converter>Find minimum key in map with Java 8 stream

Find minimum key in map with Java 8 stream

Ask Time:2017-11-22T02:49:56         Author:MazS

Json Formatter

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!

Author:MazS,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/47420537/find-minimum-key-in-map-with-java-8-stream
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(AtomicL‌​ong::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
yy