Java keySet()

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

The keyset() is a non-static method present in the EnumMap class, which is implemented by the Map class and, thus, the HashMap class. It is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them. The keySet() method is useful in iterating through the elements of the Map.

What is keySet() in Java?

The keySet() method of Map class in Java is a non-static method, i.e., to call this method an object of Map class like HashMap, TreeMap, etc. is a must. It takes no parameters and returns a Set of keys of the respective Map. This set can further be used to iterate through all the elements (key-value pairs) of the Map.

The map interface in Java contains the keySet method, which is implemented by all four maps, namely HashMap, TreeMap, LinkedHashMap, and SortedMap. It is used to iterate through all the keys of the Maps.

The keySet() method in HashMap returns keys in random order. In LinkedHashMap, it returns keys in insertion order (the same order in which we insert the values), and in TreeMap and SortedMap, it returns keys in sorted order.

keySet in Java

Syntax of keySet() in Java

Here, DT1 is the datatype of the key of the given hashmap. DT2 is the data type of the values of the respective keys. As the keySet() method returns the set of keys, the set is of the DT1 datatype.

Example:

In the above example, hm HashMap has keys of Integer data type, and values are of String data type. Here, product_ids is a set of all the ids contained in the hm as Integer data type.

Parameters of keySet() in Java

The keySet() method in Java does not take any parameters. It can be called using objects of the HashMap class.

Return Values of keySet() in Java

It returns the Set view, i.e., a Java Set of all the keys of the specified Map in random order, i.e., the order of keys is not guaranteed.

Exception for keySet() in Java

The keySet() method in Java doesn't throw any Exceptions.

Exception for keySet in Java

Example

Let us look at a simple example of storing Unicode and respective characters in a HashMap and then fetching the character using the keySet method.

Output:

In this example, we first store the first five characters and their Unicodes as keys in the HashMap. chars.keySet() returns a set of keys of chars HashMap, which is stored in codes Set. The for loop iterates through each element of the code set and prints it.

example of keySet in Java

Examples of keySet() in Java

Next, we are going to see a few examples of the keySet() method in HashMap and TreeMap. Also, we will see how we can use the keySet() method and the forEach() loop for iteration.

Example 1: Java HashMap keySet()

Let us look at an example of the keySet() method in HashMap. Let us create a Product class that is used to store various products and their details. Using the keySet() method in Java, we can print a catalog of products.

Output:

  • Product class has 4 variables, product_id, product_name, product_user, and product_country. The constructor of the Product class takes all the four parameters mentioned above and stores them in the object of the class.

  • generate_description() method takes an object of Product as a parameter and prints all the product details.

  • In the main method, we first construct objects of the Product class and put them into a HashMap, taking product_id as a key and the Product as value.

  • Further to print the catalogue, we take a set of product_id's as objects and using for-each loop and generate_description, we print the product's catalogue. hm_products.get() method returns the Product object corresponding to the product_id respectively.

Note: keySet() method in HashMap returns the keys in random order, i.e., it doesn't guarantee the same order of keys.

Example 2: Java TreeMap keyset()

TreeMap stores the keys in sorted order so that it can retrieve its components in a particular order in the minimum amount of time. Thus, the keySet() method of TreeMap also returns values in sorted order.

Let us look at an example where we store states and their capitals in a TreeMap with states as keys and capitals as values in random order.

Output:

We have entered a few states and their capitals in random order. We try to fetch the states stored in TreeMap<String,String> states_capitals using the keySet() method. In the output, the states returned are sorted in dictionary order and are different from the order in which we entered values.

Example 3: keySet() Method in for-each Loop

So far, we have created a set of all the keys in the examples and used the set in a for-each loop, but it is possible to pass the keyset method directly to the for-each loop. Let us take an example of a HashMap of different programming languages and map them to their designers or developers.

Output:

In the above example, we didn't store the values in a set separately, and we are directly passing the developers.keySet() to the for-each loop. As this method returns a set, we can also use it in the for-each loop to write compact and meaningful code.

Thus, one of the applications of keySet() in Java is to iterate through each element of the HashMap. It is simpler than calling an iterator.

Example 4: Mapping String Values to Integer Values

Let us see an example of books having unique codes consisting of letters and numbers mapped with the book ids.

Output:

In the example above, keys are of the String type, and its id is of the int type. The books.keySet() method returns a set of keys, i.e., a set of alphanumeric codes, which is passed to books. get(code) to get the ids of the books, respectively.

Example 5: Mapping Integer Values to String Values

Let us take another example of subject codes and the subjects where we store subject ids as keys and subjects as values.

Output:

In the example above, the hashmap record stores various subjects and their ids. record.keySet() returns a set of ids that are of int data type. The for-each loop prints the subjects with the help of ids.

Conclusion

  • keyset() in java is present in the Map interface. It returns a set of all the keys contained in the respective map.
  • The keySet() method doesn't take any parameters and returns a set of data of the same type as the map key. It also doesn't throw any exceptions.
  • keySet() method can be called using objects of HashMap, TreeMap, LinkedHashMap, and SortedMap. In TreeMap and SortedMap, the keySet() method in Java returns keys in sorted order.
  • keySet() method in HashMap returns keys in random order, whereas in LinkedHashMap, it returns keys in the same insertion order.
  • Instead of an iterator, we can use the keySet() method in a for-each loop to iterate through components of a Map.