First, this line does not compile :
Map<String,String> myMap = new Map<String,String>();
You cannot create an instance of an interface. In your case, it would be better to use an Hashmap since the order does not matter :
Map<String, String> myMap = new HashMap<String, String>();
Also, from Java 7, you can use the operator diamond which allows you to reduce redundant code when using the germs :
Map<String, String> myMap = new HashMap<>();
In terms of your question, from Java 8, you can use the Stream API to fulfill your need :
String key = myMap.entrySet()
.stream()
.filter(e -> e.getValue().equals("valor1"))
.findFirst()
.map(Map.Entry::getKey)
.orElse(null);
Here’s what we do here :
- Recovers the Map.Entry of your map.
- Filter flow to keep only inputs whose value is
valor1
.
- Retrieves first corresponding entry.
- Receives the value of the key.
- If no entry is found, it returns
null
.
If the code is to be used several times, it may well be encapsulated in a method :
private String getKeyByValue(final Map<String, String> map, final String value) {
return map.entrySet()
.stream()
.filter(e -> e.getValue().equals(value))
.findFirst()
.map(Map.Entry::getKey)
.orElse(null);
}
Values will not repeat themselves?
– Laerte
can assume not, or can return the first one that gives match
– ldeoliveira