Use List#contains:

if (Server.get(o).contains(value)) {
    //...
}
Answer from Luiggi Mendoza on Stack Overflow
🌐
Real's HowTo
rgagnon.com › javadetails › java-0564.html
Get keys corresponding to a value from a Map - Real's Java How-to
Cookies are used to collect and analyze information on site performance and usage. Got it This method returns a List of the keys corresponding to a given value. ... import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MapUtils { private MapUtils() {} public static List<Object> getKeysFromValue(Map<?, ?> hm, Object value){ List <Object>list = new ArrayList<Object>(); for(Object o:hm.keySet()){ if(hm.get(o).equals(value)) { list.add(o); } } return list; } public static void main(String[] argv) { Map<String, String> map = new HashMap<String, String>(); map.put("1","Homer"); map.put("2","Marge"); map.put("3","Bart"); map.put("4","Maggie"); map.put("5","Bart"); System.out.println(MapUtils.getKeysFromValue(map,"Bart")); } } [Java 1.4]
🌐
Baeldung
baeldung.com › home › java › java collections › java map › get values and keys as arraylist from a hashmap
Get Values and Keys as ArrayList From a HashMap | Baeldung
March 7, 2025 - One such scenario involves a direct association between the elements keyList[i] and valueList[i] within the original map, given an index i. In essence, elements at corresponding indices in the key and value lists exhibit correlation within the context of the original map: Map: k1 -> v1 k2 -> v2 k3 -> v3 index : 0, 1, 2 KeyList : k1, k2, k3 ValueList: v1, v2, v3 · The second scenario is relatively straightforward. Here, we aim to extract a key list and a value list from the provided map without retaining concern for the initial key-value pair associations.
🌐
Mkyong
mkyong.com › home › java › java – get keys from value hashmap
Java – Get keys from value HashMap | mkyong.com
February 26, 2021 - To find all the keys that map to a certain value, we can loop the entrySet() and Objects.equals to compare the value and get the key. Note The common mistake is use the entry.getValue().equals(value) to compare the value, because if the HashMap ...
🌐
Coderanch
coderanch.com › t › 370276 › java › key-values-arraylist
how to get the key values from a arraylist (Java in General forum at Coderanch)
Hi. The number you are writing in add(1, "ben") is the index that the new object should be inserted at. So using arr.indexOf("ben") would yield that index. However, this would be only the first index in the list if there are more elements than one that match "ben".
Find elsewhere
Top answer
1 of 16
672

If your data structure has many-to-one mapping between keys and values you should iterate over entries and pick all suitable keys:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
    Set<T> keys = new HashSet<T>();
    for (Entry<T, E> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            keys.add(entry.getKey());
        }
    }
    return keys;
}

In case of one-to-one relationship, you can return the first matched key:

public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
    for (Entry<T, E> entry : map.entrySet()) {
        if (Objects.equals(value, entry.getValue())) {
            return entry.getKey();
        }
    }
    return null;
}

In Java 8:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
    return map.entrySet()
              .stream()
              .filter(entry -> Objects.equals(entry.getValue(), value))
              .map(Map.Entry::getKey)
              .collect(Collectors.toSet());
}

Also, for Guava users, BiMap may be useful. For example:

BiMap<Token, Character> tokenToChar = 
    ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '(');
Token token = tokenToChar.inverse().get('(');
Character c = tokenToChar.get(token);
2 of 16
244

If you choose to use the Commons Collections library instead of the standard Java Collections framework, you can achieve this with ease.

The BidiMap interface in the Collections library is a bi-directional map, allowing you to map a key to a value (like normal maps), and also to map a value to a key, thus allowing you to perform lookups in both directions. Obtaining a key for a value is supported by the getKey() method.

There is a caveat though, bidi maps cannot have multiple values mapped to keys, and hence unless your data set has 1:1 mappings between keys and values, you cannot use bidi maps.


If you want to rely on the Java Collections API, you will have to ensure the 1:1 relationship between keys and values at the time of inserting the value into the map. This is easier said than done.

Once you can ensure that, use the entrySet() method to obtain the set of entries (mappings) in the Map. Once you have obtained the set whose type is Map.Entry, iterate through the entries, comparing the stored value against the expected, and obtain the corresponding key.


Support for bidi maps with generics can be found in Google Guava and the refactored Commons-Collections libraries (the latter is not an Apache project). Thanks to Esko for pointing out the missing generic support in Apache Commons Collections. Using collections with generics makes more maintainable code.


Since version 4.0 the official Apache Commons Collections™ library supports generics.

See the summary page of the "org.apache.commons.collections4.bidimap" package for the list of available implementations of the BidiMap, OrderedBidiMap and SortedBidiMap interfaces that now support Java generics.

🌐
Stack Abuse
stackabuse.com › java-how-to-get-keys-and-values-from-a-map
Java: How to Get Keys and Values from a Map
November 24, 2020 - Similarly, one may desire to retrieve and iterate through the values only, without the keys. For this, we can use values(): ... Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet.
🌐
W3docs
w3docs.com › home › code snippets › java › java hashmap: how to get key from value?
Java Hashmap: How to get key from value? | W3docs
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HashMapKeyFromValueExample { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(1, "A"); map.put(2, "B"); map.put(3, "C"); map.put(4, "D"); map.put(5, "B"); String value = "B"; List<Integer> keys = new ArrayList<>(); for (Map.Entry<Integer, String> entry : map.entrySet()) { if (value.equals(entry.getValue())) { keys.add(entry.getKey()); } } System.out.println("Keys: " + keys); } }
🌐
Stack Overflow
stackoverflow.com › questions › 22935398 › how-to-get-the-key-value-of-hashmap-which-resides-on-the-list
java - How to get the key value of HASHMAP which resides on the list - Stack Overflow
April 8, 2014 - You might want to use a single HashMap containing all rows instead (and get rid of the List): HashMap<String,String> table = new HashMap<String,String>(); while (rs.next()){ table.put(rs.getString(0),rs.getString(1)); } If you don't know in advance that the key will be in column 0 and the value will be in column 1, but you know the names of the columns, then you can loop through the columns to find the index of the one with the right name. String keyColumnName = "FROM"; int keyColumnNum = -1; // to be found for (int i = 0; i < md.getColumnCount(); i++) { if (keyColumnName.equals.getColumnName(i)) { keyColumnNum = i; break; } } // if the column exists, keyColumnNum has the right value here
🌐
Coderanch
coderanch.com › t › 676478 › java › Retrieve-key-List-Maps
How to Retrieve the key from List of Maps? (Beginning Java forum at Coderanch)
February 23, 2017 - JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility ... Assuming the input cannot be changed, you get do it quite easily using streams: [edit] fixed Objects::notNull -> Object::nonNull[/edit] SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... Let's decompose this. You have a List of Maps. A Map is a collection of name/value pairs where every name is unique.
🌐
Techie Delight
techiedelight.com › home › java › get key from value in a java map
Get key from value in a Java Map | Techie Delight
July 7, 2026 - The idea is to extend the HashMap class and overload its put() method such that it also inserts the value-key pair into a reverse map along with the key-value pair in the original map.
🌐
Baeldung
baeldung.com › home › java › java collections › java map › get the key for a value from a java map
Get the Key for a Value from a Java Map | Baeldung
July 25, 2024 - We may use another bi-directional Map called BiMap found in Guava developed by Google. This class provides a method named inverse() to get the value-key Map or the reverse Map to fetch the key based on a given value: