How to find key from an object in a map?

Xmair :

Basically, I've the following code:

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"?

The code is pretty much self explanatory. How do I get the '2'? Is it essential to use a loop?

Eran :

As an alternative to using a loop, you can use Streams to locate the key matching a given value:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=358755&siteId=1