Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

keySet()

Example

Retrieve all the keys contained within a map.

import java.util.HashMap;
public class Main {
  public static void main(String[] args) {
    HashMap<String, String> capitalCities = new HashMap<String, String>();
    capitalCities.put("England", "London");
    capitalCities.put("Germany", "Berlin");
    capitalCities.put("Norway", "Oslo");
    capitalCities.put("USA", "Washington DC");        

   
System.out.println(capitalCities.keySet());
  }
}

Definition and Usage

The keySet() method returns a set comprising all the keys present in the map.

Note: The set returned is a view of the map, implying that modifications made to the set will also affect the map.

Syntax

public Set<K> keySet()

K represents the data type of the map’s keys.

Technical Details

Returns:

A set that encompasses all the keys within the map.