First, this line does not compile:
Map<String,String> myMap = new Map<String,String>();
You can not create an instance of an interface. In your case, it would be best to use a HashMap since the order it does not matter:
Map<String, String> myMap = new HashMap<String, String>();
In addition, from Java 7, you can use the diamond operator that allows you to reduce redundant code when using generics:
Map<String, String> myMap = new HashMap<>();
In terms of your Java 8 question, you can use Stream API to fill 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:
- Retrieves the Map.Entry from your map.
- Filter the stream to keep only entries whose value is
valor1
.
- Retrieves the first matching entry.
- Get the value of the key.
- If no entry is found, it returns
null
.
If the code is to be used multiple 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);
}