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