216

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.

T J
  • 42,762
  • 13
  • 83
  • 138
Prabu
  • 3,550
  • 9
  • 44
  • 85
  • 13
    You do realise that `HashMap` entries are unordered, and so "first" could change whenever you modify the map? – NPE Oct 07 '14 at 06:57
  • 2
    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. – Jon Skeet Oct 07 '14 at 06:57
  • 1
    No, order is not guaranteed from run to run, but within the same thread, order can be relied on. – hd1 Oct 07 '14 at 06:58
  • 4
    @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...). – Bill K Aug 26 '16 at 19:30
  • @BillK: If you know each map has exactly one entry, then that's a different question really, and one that makes more sense. – Jon Skeet Aug 26 '16 at 19:48

11 Answers11

384

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();
}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • 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 – Blue Bot Nov 21 '17 at 11:03
  • @darthydarth you should use proper type based on your context. – Ruchira Gayan Ranaweera Nov 21 '17 at 11:28
  • 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 Nov 21 '17 at 11:38
  • sure but how? its too much for the comments section – Blue Bot Nov 21 '17 at 12:55
  • @darthydarth you can send me an email. ruchiragayan@gmail.com – Ruchira Gayan Ranaweera Nov 21 '17 at 15:58
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/159539/discussion-between-ruchira-gayan-ranaweera-and-darthydarth). – Ruchira Gayan Ranaweera Nov 22 '17 at 03:29
  • @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. – Ruchira Gayan Ranaweera Dec 11 '17 at 12:37
  • @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]`? – Simon Baars Dec 11 '17 at 12:54
  • Quick Question: is `map.entrySet().iterator().next()` a o(1) runtime or o(n) runtime. Thanks if anyone can answer... – Fiddle Freak Apr 29 '21 at 10:21
100

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
60

Java 8 way of doing,

String firstKey = map.keySet().stream().findFirst().get();

whoami
  • 1,517
  • 1
  • 21
  • 29
  • 3
    if we have the key, retrieve the first value using map.get(firstKey). Just a hint. :) – Upen Aug 30 '19 at 22:42
  • 2
    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! – Tobias Kaufmann Feb 03 '21 at 17:07
12

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();
Georgios Syngouroglou
  • 18,813
  • 9
  • 90
  • 92
  • I've noticed that if you know the map only contains 1 value, the iterator `keys.values().iterator().next();` is much faster than the `keys.values().stream().findFirst().get();` If you know the function is going to be called often, and most of the time the map will hold only one value, this might be a performance optimization. – BarbetNL Jul 14 '22 at 20:42
8

Kotlin Answer

Get first key then get value of key. Kotlin has "first()" function:

val list = HashMap<String, String>() // Dummy HashMap.

val keyFirstElement = list.keys.first() // Get key.

val valueOfElement = list.getValue(keyFirstElement) // Get Value.
canerkaseler
  • 6,204
  • 45
  • 38
4

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

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
4

Note that you should note that your logic flow must never rely on accessing the HashMap elements in some order, simply put because HashMaps are not ordered Collections and that is not what they are aimed to do. (You can read more about odered and sorter collections in this post).

Back to the post, you already did half the job by loading the first element key:

Object myKey = statusName.keySet().toArray()[0];

Just call map.get(key) to get the respective value:

Object myValue = statusName.get(myKey);
Community
  • 1
  • 1
tmarwen
  • 15,750
  • 5
  • 43
  • 62
1

Remember that the insertion order isn't respected in a map generally speaking. Try this :

    /**
     * Get the first element of a map. A map doesn't guarantee the insertion order
     * @param map
     * @param <E>
     * @param <K>
     * @return
     */
    public static <E,K> K getFirstKeyValue(Map<E,K> map){
        K value = null;
        if(map != null && map.size() > 0){
            Map.Entry<E,K> entry =  map.entrySet().iterator().next();
            if(entry != null)
                value = entry.getValue();
        }
        return  value;
    }

I use this only when I am sure that that map.size() == 1 .

Maxime Claude
  • 965
  • 12
  • 27
1

Improving whoami's answer. Since findFirst() returns an Optional, it is a good practice to check if there is a value.

 var optional = pair.keySet().stream().findFirst();

 if (!optional.isPresent()) {
    return;
 }

 var key = optional.get();

Also, some commented that finding first key of a HashSet is unreliable. But sometimes we have HashMap pairs; i.e. in each map we have one key and one value. In such cases finding the first key of such a pair quickly is convenient.

Jan Bodnar
  • 10,969
  • 6
  • 68
  • 77
0

Also a nice way of doing this :)

Map<Integer,JsonObject> requestOutput = getRequestOutput(client,post);
int statusCode = requestOutput.keySet().stream().findFirst().orElseThrow(() -> new RuntimeException("Empty"));
Adrian
  • 947
  • 1
  • 12
  • 24
-3

You can also try below:

Map.Entry<String, Integer> entry = myMap.firstEntry();
System.out.println("First Value = " + entry);
justhalf
  • 8,960
  • 3
  • 47
  • 74
Veera
  • 11