I have a HashMap<Integer, Integer>
and i'm willing to get the key of a specific value.
for example my HashMap:
Key|Vlaue
2--->3
1--->0
5--->1
I'm looking for a java stream operation to get the key that has the maximum value. In our example the key 2 has the maximum value.
So 2 should be the result.
with a for loop it can be possible but i'm looking for a java stream way.
import java.util.*;
public class Example {
public static void main( String[] args ) {
HashMap <Integer,Integer> map = new HashMap<>();
map.put(2,3);
map.put(1,0);
map.put(5,1);
/////////
}
}
You can stream over the entries, find the max value and return the corresponding key:
Integer maxKey =
map.entrySet()
.stream() // create a Stream of the entries of the Map
.max(Comparator.comparingInt(Map.Entry::getValue)) // find Entry with
// max value
.map(Map.Entry::getKey) // get corresponding key of that Entry
.orElse (null); // return a default value in case the Map is empty
public class GetSpecificKey{
public static void main(String[] args) {
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
map.put(2,3);
map.put(1,0);
map.put(5,1);
System.out.println(
map.entrySet().stream().
max(Comparator.comparingInt(Map.Entry::getValue)).
map(Map.Entry::getKey).orElse(null));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With