HashMap - getting First Key value
Solution 1
You can try this:
Map<String,String> map = new HashMap<>();
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key = entry.getKey();
String value = entry.getValue();
Keep in mind, HashMap
does not guarantee the insertion order. Use a LinkedHashMap
to keep the order intact.
Eg:
Map<String,String> map = new LinkedHashMap<>();
map.put("Active","33");
map.put("Renewals Completed","3");
map.put("Application","15");
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key= entry.getKey();
String value=entry.getValue();
System.out.println(key);
System.out.println(value);
Output:
Active
33
Update:
Getting first key in Java 8
or higher versions.
Optional<String> firstKey = map.keySet().stream().findFirst();
if (firstKey.isPresent()) {
String key = firstKey.get();
}
Solution 2
To get the "first" value:
map.values().toArray()[0]
To get the value of the "first" key:
map.get(map.keySet().toArray()[0])
Note: Above code tested and works.
I say "first" because HashMap entries are not ordered.
However, a LinkedHashMap iterates its entries in the same order as they were inserted - you could use that for your map implementation if insertion order is important.
Solution 3
Java 8 way of doing,
String firstKey = map.keySet().stream().findFirst().get();
Solution 4
You may also try the following in order to get the entire first entry,
Map.Entry<String, String> entry = map.entrySet().stream().findFirst().get();
String key = entry.getKey();
String value = entry.getValue();
The following shows how you may get the key of the first entry,
String key = map.entrySet().stream().map(Map.Entry::getKey).findFirst().get();
// or better
String key = map.keySet().stream().findFirst().get();
The following shows how you may get the value of the first entry,
String value = map.entrySet().stream().map(Map.Entry::getValue).findFirst().get();
// or better
String value = map.values().stream().findFirst().get();
Moreover, in case wish to get the second (same for third etc) item of a map and you have validated that this map contains at least 2 entries, you may use the following.
Map.Entry<String, String> entry = map.entrySet().stream().skip(1).findFirst().get();
String key = map.keySet().stream().skip(1).findFirst().get();
String value = map.values().stream().skip(1).findFirst().get();
Solution 5
how can we collect the first Key "Value" (i.e 33)
By using youMap.get(keyYouHave)
, you can get the value of it.
want to store the Both "Key" and "Value" in separate variable
Yes, you can assign that to a variable.
Wait .........it's not over.
If you(business logic) are depending on the order of insertions and retrieving, you are going to see weird results. Map is not ordered they won't store in an order. Please be aware of that fact. Use some alternative to preserve your order. Probably a LinkedHashMap
Related videos on Youtube
Prabu
Automation Test Engineer Selenium WebDriver Katalon Studio Java / Groovy
Updated on July 08, 2022Comments
-
Prabu almost 2 years
Below are the values contain in the HashMap
statusName {Active=33, Renewals Completed=3, Application=15}
Java code to getting the first Key (i.e Active)
Object myKey = statusName.keySet().toArray()[0];
How can we collect the first Key "Value" (i.e 33), I want to store both the "Key" and "Value" in separate variable.
-
NPE over 9 yearsYou do realise that
HashMap
entries are unordered, and so "first" could change whenever you modify the map? -
Jon Skeet over 9 yearsDo you understand that there's no specific order in a
HashMap
? If you modify it at all, you may get the results in a completely different order. -
hd1 over 9 yearsNo, order is not guaranteed from run to run, but within the same thread, order can be relied on.
-
Bill K almost 8 years@JonSkeet Actually this is a really valid question. In Groovy there are a lot of cases where you get back a structure that looks like a list of maps, each map with a single entry. So far I have not found an easy/obvious(Groovy) way to print out all the values. If the keys are constant, it's as easy as collection.each{println it.key} to print out each value, but without constant keys it's not obvious, but collection.each{println it.values()[0]} works (A refinement of some of the answers here...).
-
Jon Skeet almost 8 years@BillK: If you know each map has exactly one entry, then that's a different question really, and one that makes more sense.
-
-
Blue Bot over 6 yearsI know this is an very old answer.. this is working for hashmaps with key and value as strings. but when trying the same with object for a value getting casting error:
com.google.gson.internal.LinkedTreeMap cannot be cast to...
... my class which I stated instead of theString
in the right place... can't find answer online..help -
Ruchira Gayan Ranaweera over 6 years@darthydarth you should use proper type based on your context.
-
Blue Bot over 6 yearsfirst super thanks for answering! was not expecting it... second I do, found that there is an issue with Generics not saved in runtime. eventually I hacked around it by using
Gson
to convert value object to aString
and then parse it back to my class type. Its ugly but I really could not find any other solution to something that is so easy to do in other languages (I learing Java now) -
Blue Bot over 6 yearssure but how? its too much for the comments section
-
Ruchira Gayan Ranaweera over 6 years@darthydarth you can send me an email. [email protected]
-
Ruchira Gayan Ranaweera over 6 yearsLet us continue this discussion in chat.
-
Ruchira Gayan Ranaweera over 6 years@SimonBaars No, HashMap does not thread safe by design. But you can make it thread safe based on your use of the HashMap. You can directly use HashTable but you should keep in mind it also has performance concern over HashMap.
-
Simon Baars over 6 years@RuchiraGayanRanaweera What would be the code when trying to retrieve the first element threadsave using a java.util.Hashtable? And wouldn't the following be threadsafe:
map.keySet().toArray()[0]
? -
Adrian Grygutis about 6 yearsThere's no such method
-
ACV almost 6 yearsyou first need to check that the map is not empty
-
Upen almost 5 yearsif we have the key, retrieve the first value using map.get(firstKey). Just a hint. :)
-
Tobias Kaufmann over 3 yearsDo NOT use this approach! If the
map
variable is from type HashMap, this will NOT work reliably, convert to an Array or LinkedHashMap instead! -
Fiddle Freak about 3 yearsQuick Question: is
map.entrySet().iterator().next()
a o(1) runtime or o(n) runtime. Thanks if anyone can answer...