Get keys from HashMap in Java

Get keys from HashMap in Java

In Java, you can retrieve the keys from a HashMap using the keySet() method. The keySet() method returns a Set of keys, which you can iterate through or convert to other data structures as needed. Here's how you can get the keys from a HashMap:

import java.util.HashMap; import java.util.Map; import java.util.Set; public class Main { public static void main(String[] args) { // Create a HashMap Map<String, Integer> hashMap = new HashMap<>(); // Add some key-value pairs to the HashMap hashMap.put("one", 1); hashMap.put("two", 2); hashMap.put("three", 3); hashMap.put("four", 4); // Get the keys from the HashMap Set<String> keys = hashMap.keySet(); // Iterate through the keys and print them for (String key : keys) { System.out.println("Key: " + key); } } } 

In this example, we first create a HashMap called hashMap and add some key-value pairs to it. Then, we use the keySet() method to obtain a Set of keys from the HashMap. Finally, we iterate through the set of keys using a for loop and print each key.

This will output:

Key: one Key: two Key: three Key: four 

You can use the keys obtained in the Set for various purposes, such as accessing corresponding values or performing other operations on the keys.


More Tags

pdfkit master-pages cs50 dma insert-update blazor model-view-controller xml msgpack 360-degrees

More Java Questions

More Cat Calculators

More Physical chemistry Calculators

More Biology Calculators

More Chemistry Calculators