English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I)/O)

Java Reader/Writer

Java other topics

Usage and example of Java HashMap keySet()

Java HashMap Methods

The Java HashMap keySet() method returns a view of the set of all keys contained in the hash table entries.

The syntax of the keySet() method is: }}

hashmap.keySet()

keySet() parameters

The keySet() method does not take any parameters.

The return value of keySet()

  •  Returns the set view of all keys of the hash map

Note: The collection view only displays all keys of the hash map as a collection. It does not contain the actual keys.

Example1: Java HashMap keySet()

import java.util.HashMap;
class Main {
  public static void main(String[] args) {
    // Create a HashMap
    HashMap<String, Integer> prices = new HashMap<>();
    // Insert entries into the HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: "); + prices);
    // Returns a set view of all keys
    System.out.println("Keys: "); + prices.keySet());
  }
}

Output Result

HashMap: {Pant =150, Bag =300, Shoes =200}
Keys: [Pant, Bag, Shoes]

In the above example, we created a hash map named prices. Note the expression

prices.keySet()

Here, the keySet() method returns a set view of all keys existing in the hash map.

The keySet() method can also be used withfor-The each loopused together to iterate over each key in the hash map.

Example2: for-The keySet() method in the each loop

import java.util.HashMap;
class Main {
  public static void main(String[] args) {
    // Create a HashMap
    HashMap<String, Integer> numbers = new HashMap<>();
    numbers.put("One", 1);
    numbers.put("Two", 2);
    numbers.put("Three", 3);
    System.out.println("HashMap: "); + numbers);
    //Access all keys of the HashMap
    System.out.print("Keys: ");
    //keySet() returns a set view of all keys
    //for-The loop iterates over each key in the view
    for (String key : numbers.keySet()) {
      // Print each key
      System.out.print(key + ", ");
    }
  }
}

Output Result

HashMap: {One=1, Two=2, Three=3}
Keys: One, Two, Three,

In the above example, we created a hash map named numbers. Note this line,

String key: numbers.keySet()

Here, the keySet() method returnsall keysofSet collection view. The variable key accesses each key from the view.

Note: The keys of HashMap are of String type. Therefore, we use a String variable to access the keys.

Related Reading

Java HashMap Methods