Xmair:
Basicamente, eu tenho o seguinte código:
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"?
O código é bastante auto-explicativo. Como faço para obter o '2'? É essencial usar um loop?
Eles foram:
Como uma alternativa ao uso de um loop, você pode usar Stream
s para localizar a chave correspondente um dado valor:
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