Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a specific key from HashMap using java stream

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);
         /////////

     }
}
like image 458
xmen-5 Avatar asked Dec 09 '18 13:12

xmen-5


2 Answers

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
like image 158
Eran Avatar answered Nov 13 '22 01:11

Eran


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));
}

}

like image 1
Avvappa Hegadyal Avatar answered Nov 13 '22 01:11

Avvappa Hegadyal