How to get all map keys having given value in Java

3 Answers

0 votes
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.HashSet;

public class MyClass
{
    public static <K, V> Set<K> GetKeys(Map<K, V> mp, V value) {
        Set<K> keys = new HashSet<>();
        for (Map.Entry<K, V> entry: mp.entrySet()) {
            if (value.equals(entry.getValue())) {
                keys.add(entry.getKey());
            }
        }
        return keys;
    }
 
    public static void main(String[] args)
    {
        Map<String, Integer> mp = new HashMap();
        
        mp.put("java", 1);
        mp.put("c", 1);
        mp.put("c++", 2);
        mp.put("c#", 1);
        mp.put("python", 3);
        mp.put("rust", 4);
 
        System.out.println(GetKeys(mp, 1));
    }
}




/*
run:

[c#, java, c]

*/

 



answered Mar 27, 2023 by avibootz
0 votes
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.stream.Stream;
import java.util.stream.Collectors;

public class MyClass
{
    public static <K, V> Set<K> GetKeys(Map<K, V> mp, V value) {
        return mp.entrySet().stream()
                .filter(entry -> value.equals(entry.getValue()))
                .map(Map.Entry::getKey)
                .collect(Collectors.toSet());
    }
 
    public static void main(String[] args)
    {
        Map<String, Integer> mp = new HashMap();
        
        mp.put("java", 1);
        mp.put("c", 1);
        mp.put("c++", 2);
        mp.put("c#", 1);
        mp.put("python", 3);
        mp.put("rust", 4);
 
        System.out.println(GetKeys(mp, 1));
    }
}




/*
run:

[c#, java, c]

*/

 



answered Mar 27, 2023 by avibootz
0 votes
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.stream.Stream;
import java.util.stream.Collectors;

public class MyClass
{
    public static <K, V> Set<K> GetKeys(Map<K, V> mp, V value) {
        return mp.keySet().stream()
                .filter(key -> value.equals(mp.get(key)))
                .collect(Collectors.toSet());
    }
 
    public static void main(String[] args)
    {
        Map<String, Integer> mp = new HashMap();
        
        mp.put("java", 1);
        mp.put("c", 1);
        mp.put("c++", 2);
        mp.put("c#", 1);
        mp.put("python", 3);
        mp.put("rust", 4);
 
        System.out.println(GetKeys(mp, 1));
    }
}




/*
run:

[c#, java, c]

*/

 



answered Mar 27, 2023 by avibootz

Related questions

1 answer 127 views
127 views asked Nov 17, 2023 by avibootz
2 answers 151 views
1 answer 165 views
1 answer 88 views
...