HashMap – getting First Key value

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)