首页 文章

使用java stream从HashMap获取特定键

提问于
浏览
5

我有 HashMap<Integer, Integer> 并且我愿意获得特定值的密钥 .

例如我的HashMap:

Key|Vlaue
2--->3
1--->0
5--->1

我正在寻找一个java流操作来获取具有最大值的密钥 . 在我们的示例中,键2具有最大值 .

所以2应该是结果 .

使用for循环它是可能的,但我正在寻找一种java流方式 .

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

     }
}

2 回答

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

    }

  • 1

    您可以对条目进行流式处理,找到最大值并返回相应的键:

    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
    

相关问题