【问题标题】:get a specific key from HashMap using java stream使用 java 流从 HashMap 获取特定键
【发布时间】:2019-05-10 14:34:06
【问题描述】:

我有一个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);
         /////////

     }
}

【问题讨论】:

    标签: java java-8 hashmap java-stream


    【解决方案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
    

    【讨论】:

      【解决方案2】:
      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));
      }
      

      }

      【讨论】:

        猜你喜欢
        • 2014-12-03
        • 1970-01-01
        • 1970-01-01
        • 2010-11-25
        • 2016-03-08
        • 1970-01-01
        • 2015-09-26
        • 2019-05-20
        相关资源
        最近更新 更多