is there a way to find out all the key which having same value in the map. Like
map.put("A","Abc");
map.put("B","Abc");
map.put("C","Abc");
map.put("D","Bcd");
Here I want to find out all the key which having value "Abc".
is there a way to find out all the key which having same value in the map. Like
map.put("A","Abc");
map.put("B","Abc");
map.put("C","Abc");
map.put("D","Bcd");
Here I want to find out all the key which having value "Abc".
Find all "x", such that "y" is called filtering
.
This is how you can filter using Java 8 Streams:
Stream<String> keys = map.entrySet().stream()
.filter(x -> "Abc".equals(x.getValue()))
.map(Map.Entry::getKey);
For Java 7, you have to do it manually:
List<String> keys = new ArrayList<>();
for(Map.Entry<String, String> e : map.entrySet())
if("Abc".equals(e.getValue()))
keys.add(e.getKey());
You could also use Guava filter.
Map<String, String> map = Maps.newHashMap();
map.put("A", "abc");
map.put("B", "abc");
map.put("C", "a3c");
map.put("D", "abc");
final String str = "a3c";
Map<String, String> filteredMap = Maps.filterEntries(map, new Predicate<Map.Entry<String, String>>() {
@Override
public boolean apply(final Map.Entry<String, String> stringStringEntry) {
return stringStringEntry.getValue().equals(str);
}
});
This would return a Map of all the map entries which have str
as a value.
FYI I only provided the function definition to show what it was doing however I would suggest using the predefined Predicates eg:
Map<String, String> filteredMap = Maps.filterValues(map, Predicates.equalTo(str));
Yes, there is a way. You can obtain a list of key-value pairs from the map. And then it's just a matter of filtering out the keys that map to your specific value.
Like so for example:
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("A", "Abc");
map.put("B", "Abc");
map.put("C", "Abc");
map.put("D", "Bcd");
Set<Entry<String, String>> set = map.entrySet();//<-- get key-value pairs
for(Entry<String, String> entry : set){//<-- iterate over all entries
if(entry.getValue().equals("Abc")){//<-- check for your value
System.out.println(entry.getKey());//<-- print the key / or add it to a list if you want
}
}
}
I hope this helps :)