HashMap - getting First Key value

JavaHashmap

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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 - Java

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

Java 8 way of doing,

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

Solution 4 - Java

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 - Java

>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

Solution 6 - Java

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.

Solution 7 - Java

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);

Solution 8 - Java

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 .

Solution 9 - Java

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.

Solution 10 - Java

Also a nice way of doing this :)

Map<Integer,JsonObject> requestOutput = getRequestOutput(client,post);
int statusCode = requestOutput.keySet().stream().findFirst().orElseThrow(() -> new RuntimeException("Empty"));

Solution 11 - Java

You can also try below:

Map.Entry<String, Integer> entry = myMap.firstEntry();
System.out.println("First Value = " + entry);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrabuView Question on Stackoverflow
Solution 1 - JavaRuchira Gayan RanaweeraView Answer on Stackoverflow
Solution 2 - JavaBohemianView Answer on Stackoverflow
Solution 3 - JavawhoamiView Answer on Stackoverflow
Solution 4 - JavaGeorgios SyngouroglouView Answer on Stackoverflow
Solution 5 - JavaSuresh AttaView Answer on Stackoverflow
Solution 6 - JavaNamelessView Answer on Stackoverflow
Solution 7 - JavatmarwenView Answer on Stackoverflow
Solution 8 - JavaMaxime ClaudeView Answer on Stackoverflow
Solution 9 - JavaJan BodnarView Answer on Stackoverflow
Solution 10 - JavaAdrianView Answer on Stackoverflow
Solution 11 - JavaVeeraView Answer on Stackoverflow