HashMap - getting First Key value

444,138

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

Share:
444,138

Related videos on Youtube

Prabu
Author by

Prabu

Automation Test Engineer Selenium WebDriver Katalon Studio Java / Groovy

Updated on July 08, 2022

Comments

  • Prabu
    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
      NPE over 9 years
      You do realise that HashMap entries are unordered, and so "first" could change whenever you modify the map?
    • Jon Skeet
      Jon Skeet over 9 years
      Do 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
      hd1 over 9 years
      No, order is not guaranteed from run to run, but within the same thread, order can be relied on.
    • Bill K
      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
      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
    Blue Bot over 6 years
    I 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 the String in the right place... can't find answer online..help
  • Ruchira Gayan Ranaweera
    Ruchira Gayan Ranaweera over 6 years
    @darthydarth you should use proper type based on your context.
  • Blue Bot
    Blue Bot over 6 years
    first 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 a String 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
    Blue Bot over 6 years
    sure but how? its too much for the comments section
  • Ruchira Gayan Ranaweera
    Ruchira Gayan Ranaweera over 6 years
    @darthydarth you can send me an email. [email protected]
  • Ruchira Gayan Ranaweera
    Ruchira Gayan Ranaweera over 6 years
  • Ruchira Gayan Ranaweera
    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
    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
    Adrian Grygutis about 6 years
    There's no such method
  • ACV
    ACV almost 6 years
    you first need to check that the map is not empty
  • Upen
    Upen almost 5 years
    if we have the key, retrieve the first value using map.get(firstKey). Just a hint. :)
  • Tobias Kaufmann
    Tobias Kaufmann over 3 years
    Do 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
    Fiddle Freak about 3 years
    Quick Question: is map.entrySet().iterator().next() a o(1) runtime or o(n) runtime. Thanks if anyone can answer...