How to get map key in java

Java Hashmap: How to get key from value?

If I have the value «foo» , and a HashMap ftw for which ftw.containsValue(«foo») returns true , how can I get the corresponding key? Do I have to loop through the hashmap? What is the best way to do that?

Note that there is no single corresponding key — there may well be multiple keys mapping to the same value.

39 Answers 39

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 Set getKeysByValue(Map map, E value) < Setkeys = new HashSet(); for (Entry 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 getKeyByValue(Map map, E value) < for (Entryentry : map.entrySet()) < if (Objects.equals(value, entry.getValue())) < return entry.getKey(); >> return null; > 
public static Set getKeysByValue(Map 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 tokenToChar = ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '('); Token token = tokenToChar.inverse().get('('); Character c = tokenToChar.get(token); 

I have thought the same solution, I have upvoted it of course but I doubt on its efficiency when it comes to really large Collections.

Читайте также:  Css classes in php

stackoverflow.com/questions/4553624/hashmap-get-put-complexity HashMap has time complexity o(1) . If you are iterating over the values then it will kill the performance. If you want a better performance and has a one-one relationship, you can use another map where value is a key

I recommend to replace .filter(entry -> entry.getValue().equals(value)) with .filter(entry -> Objects.equals (entry.getValue(), value)) as no statement about null ability was made. Further, you can replace .map(entry -> entry.getKey()) with .map(Map.Entry::getKey)

i’m having difficulty understanding the notation before Set getKeysByValue(). what’s the point. different way to do it without using that? thanks

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.

Источник

Java: How to Get Keys and Values from a Map

Key-value stores are essential and often used, especially in operations that require fast and frequent lookups. They allow an object — the key — to be mapped to another object, the value. This way, the values can easily be retrieved, by looking up the key.

In Java, the most popular Map implementation is the HashMap class. Aside from key-value mapping, it’s used in code that requires frequest insertions, updates and lookups. The insert and lookup time is a constant O(1).

In this tutorial, we’ll go over how to get the Keys and Values of a map in Java.

Get Keys and Values (Entries) from Java Map

Most of the time, you’re storing key-value pairs because both pieces of info are important. Thus, in most cases, you’ll want to get the key-value pair together.

The entrySet() method returns a set of Map.Entry objects that reside in the map. You can easily iterate over this set to get the keys and their associated values from a map.

Let’s populate a HashMap with some values:

Map map = new HashMap<>(); map.put("David", 24); map.put("John", 35); map.put("Jane", 19); map.put("Billy", 21); 

Now, let’s iterate over this map, by going over each Map.Entry in the entrySet() , and extracing the key and value from each of those entries:

for (Map.Entry pair : map.entrySet()) < System.out.println(String.format("Key (name) is: %s, Value (age) is : %s", pair.getKey(), pair.getValue())); > 
Key (name) is: Billy, Value (age) is: 21 Key (name) is: David, Value (age) is: 24 Key (name) is: John, Value (age) is: 35 Key (name) is: Jane, Value (age) is: 19 

Get Keys and Values (Entries) from Java Map with forEach()

Java 8 introduces us to the forEach() method for collections. It accepts a BiConsumer action . The forEach() method performs the given BiConsumer action on each entry of the HashMap .

Let’s use the same map from before, but this time, add a year to each of the entries’ ages:

map.forEach((key, value) -> System.out.println(key + " : " + value)); 
Billy : 21 David : 24 John : 35 Jane : 19 

Or, instead of consuming each key and value from the map, you can use a regular Consumer and just consume entire entries from the entrySet() :

map.entrySet() .forEach((entry) -> System.out.println(entry.getKey() + " : " + entry.getValue())); 
Billy : 21 David : 24 John : 35 Jane : 19 

Get Keys from a Java Map

To retrieve just keys, if you don’t really need any information from the values, instead of the entry set, you can get the key set:

Get Values from a Java Map

Similarly, one may desire to retrieve and iterate through the values only, without the keys. For this, we can use values() :

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

for(String value: map.values())

Check if Map Contains a Key

The HashMap class has a containsKey() method, which checks if the passed key exists in the HashMap , and returns a boolean value signifying the presence of the element or lack thereof.

Let’s check if a key, 5 exists:

boolean result = map.containsKey(5); System.out.println(result); 
boolean result = map.containsKey("John"); System.out.println(result); 

Conclusion

In this article, we’ve gone over a few ways to get keys and values (entries) of a Map in Java. We’ve covered using an iterator and going through each Map.Entry , as well as using a forEach() method both on the map itself, as well as its entry set.

Finally, we’ve gone over how to get the key set and values separately, and check if a map contains a given key.

Источник

Java — how to get a key object (or entry) stored in HashMap by key?

A HashMap uses equals() , which is the same for multiple unique objects. So I want to get the actual key from the map, which will always be the same, no matter what object was used to query the map. Is there a way to get the actual key object from the map? I don’t see anything in the interface, but perhaps some clever trick I overlooked? (Iterating all entries or keys doesn’t count.)

For what purpose? The only times you care about the actual object identity is if you are either synchronising or misusing == . NB a hash map uses both hashCode() and equals() .

Re: «A HashMap uses hashCode() , which is the same for multiple unique objects»: More relevantly, it uses equals() rather than == . The hashCode() is just for quickly narrowing down the set of keys that it needs to use equals() on.

What is unclear both this time and the previous time you asked this question is why you are asking it. At least last time you had a reason, although the code you posted was actually meaningless. This time, nothing, not even when you were specifically asked for an explanation, 23 minutes and several edits ago.

If your design depends on getting a reference to a specific instance, the key instance that was originally passed to put(K,V) , and an equivalent (via hashCode() and equals() ) is insufficient, then your design is broken. Unless you can provide a convincing reason for wanting this we have to assume it’s an XY Problem.

Why you ask does matter: when the question appears pointless; when you are asked; when what you are asking looks like an XY problem; and when your previous motivation for asking it proved spurious. Are you perhaps looking for IdentityHashMap ?

5 Answers 5

Is there a way to get the actual key object from the map?

OK, so I am going to make some assumptions about what you mean. After all, you said that your question doesn’t need clarification, so the obvious meaning that I can see must be the correct one. Right? 🙂

The answer is No. There isn’t a way.

Example scenario (not compileable!)

UUID uuid = UUID.fromString("xxxx-yyy-zzz"); UUID uuid2 = UUID.fromString("xxxx-yyy-zzz"); // same string println(uuid == uuid2); // prints false println(uuid.equals(true)); // prints true Map map = new . map.put(uuid, "fred"); println(map.get(uuid)); // prints fred println(map.get(uuid2)); // prints fred (because uuid.equals(uuid2) is true) 

. but, the Map API does not provide a way to find the actual key (in the example above it is uuid ) in the map apart from iterating the key or entry sets. And I’m not aware of any existing Map class (standard or 3rd-party) that does provide this 1 .

However, you could implement your own Map class with an additional method for returning the actual key object. There is no technical reason why you couldn’t, though you would have more code to write, test, maintain, etcetera.

But I would add that I agree with Jim Garrison. If you have a scenario where you have UUID objects (with equality-by-value semantics) and you also want to implement equality by identity semantics, then there is probably something wrong with your application’s design. The correct approach would be to change the UUID.fromString(. ) implementation to always return the same UUID object for the same input string.

1 — This is not to say that such a map implementation doesn’t exist. But if it does, you should be able to find it if you look hard enough Note that Questions asking us to find or recommend a library are off-topic!

Источник

How to get values and keys from HashMap?

I’m writing a simple edit text in Java. When the user opens it, a file will be opened in JTabbedPane . I did the following to save the files opened: HashMap hash = new HashMap(); Where Tab will receive the values, such as: File file, JTextArea container, JTabbedPane tab . I have a class called Tab :

public Tab(File file, JTextArea container, JTabbedPane tab)

11 Answers 11

To get all the values from a map:

To get all the entries from a map:

for ( Map.Entry entry : hash.entrySet()) < String key = entry.getKey(); Tab tab = entry.getValue(); // do something with key and/or tab >

Java 8 update:

hash.values().forEach(tab -> /* do something with tab */); 
hash.forEach((key, tab) -> /* do something with key and tab */); 

Map is internally made up of Map.Entry objects. Each Entry contains key and value . To get key and value from the entry you use accessor and modifier methods.

If you want to get values with given key , use get() method and to insert value, use put() method.

#Define and initialize map; Map map = new HashMap(); map.put("USA",1) map.put("Japan",3) map.put("China",2) map.put("India",5) map.put("Germany",4) map.get("Germany") // returns 4 

If you want to get the set of keys from map, you can use keySet() method

Set keys = map.keySet(); System.out.println("All keys are: " + keys); // To get all key: value for(String key: keys)

Generally, To get all keys and values from the map, you have to follow the sequence in the following order:

  • Convert Hashmap to MapSet to get set of entries in Map with entryset() method.:
    Set st = map.entrySet();
  • Get the iterator of this set:
    Iterator it = st.iterator();
  • Get Map.Entry from the iterator:
    Map.Entry entry = it.next();
  • use getKey() and getValue() methods of the Map.Entry to get keys and values.
// Now access it Set st = (Set) map.entrySet(); Iterator it = st.iterator(); while(it.hasNext())

In short, use iterator directly in for

for(Map.Entry entry:map.entrySet())

Источник

Оцените статью