Search code examples
javahashmap

HashMap - getting First Key value


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.


Solution

  • 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();
    }