簡體   English   中英

使用java流從HashMap獲取特定鍵

[英]get a specific key from HashMap using java stream

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

     }
}

您可以對條目進行流式處理,找到最大值並返回相應的鍵:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM