How to get the first key value of a HashMap in Java

1 Answer

0 votes
import java.util.HashMap;
import java.util.Map;
 
public class MyClass {
    public static void main(String args[]) {
        HashMap<String, Integer> hm = new HashMap<>();
  
        hm.put("Java", 423);
        hm.put("C++", 756);
        hm.put("Python", 908);
        hm.put("C", 183);
        hm.put("PHP", 302);
  
        Map.Entry<String, Integer> firstEntry = hm.entrySet().iterator().next();
        String firstKey = firstEntry.getKey();
        Integer firstValue = firstEntry.getValue();

        System.out.println("First key: " + firstKey);
        System.out.println("First value: " + firstValue);
    }
}
   
   
   
   
/*
run:
     
First key: Java
First value: 423
   
*/

 



answered Oct 16, 2023 by avibootz

Related questions

1 answer 121 views
121 views asked Oct 24, 2023 by avibootz
1 answer 171 views
2 answers 207 views
2 answers 285 views
1 answer 178 views
1 answer 281 views
...