どのようにマップ内のオブジェクトからキーを見つけるには?

Xmair:

基本的に、私は次のコードをしました:

Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "test");
map.put(2, "test2");
// I can get the string using this:
String str = map.get("test2");
// but how do I get the index ('key') of "test2"?

コードはかなり自明です。どのように私は「2」を得るのですか?ループを使用することが不可欠ですか?

彼らは次のとおりでした:

ループを使用する代わりに、あなたは使うことができStream、与えられた値と一致するキーを見つけ秒:

map.entrySet()
   .stream() // build a Stream<Map.Entry<Integer,String> of all the map entries
   .filter(e -> e.getValue().equals("test2")) // locate entries having the required value
   .map(Map.Entry::getKey) // map to the corresponding key
   .findFirst() // get the first match (there may be multiple matches)
   .orElse(null); // default value in case of no match

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=363869&siteId=1