2

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

avk
  • 871
  • 1
  • 9
  • 22
Anil Darji
  • 45
  • 2
  • 8
  • Yes, there is - see [this question](http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value). – Glorfindel Jun 13 '15 at 14:17

3 Answers3

4

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());
folkol
  • 4,752
  • 22
  • 25
3

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));
AdamSkywalker
  • 11,408
  • 3
  • 38
  • 76
steves165
  • 74
  • 2
  • 7
0

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 :)

Roan
  • 1,200
  • 2
  • 19
  • 32