xmen-5
xmen-5

Reputation: 1906

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

     }
}

Upvotes: 6

Views: 713

Answers (2)

Avvappa Hegadyal
Avvappa Hegadyal

Reputation: 273

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

}

Upvotes: 1

Eran
Eran

Reputation: 393801

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

Upvotes: 10

Related Questions