Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java hashmap methods.

  • Java HashMap clear()
  • Java HashMap clone()
  • Java HashMap isEmpty()
  • Java HashMap size()
  • Java HashMap put()
  • Java HashMap putAll()
  • Java HashMap putIfAbsent()
  • Java HashMap remove()
  • Java HashMap containsKey()
  • Java HashMap containsValue()
  • Java HashMap replace()
  • Java HashMap replaceAll()
  • Java HashMap get()
  • Java HashMap getOrDefault()

Java HashMap forEach()

Java HashMap entrySet()

Java HashMap keySet()

Java HashMap values()

  • Java HashMap merge()
  • Java HashMap compute()
  • Java HashMap computeIfAbsent()

Java HashMap computeIfPresent()

Java Tutorials

The syntax of the keySet() method is:

Here, hashmap is an object of the HashMap class.

keySet() Parameters

The keySet() method does not take any parameter.

keySet() Return Value

  • returns a set view of all the keys of the hashmap

Note : The set view only shows all keys of the hashmap as a set. The view does not contain actual keys. To learn more about view in Java, visit the view of a collection .

Example 1: Java HashMap keySet()

In the above example, we have created a hashmap named prices . Notice the expression,

Here, the keySet() method returns a set view of all the keys present in the hashmap.

The keySet() method can also be used with the for-each loop to iterate through each key of the hashmap.

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

In the above example, we have created a hashmap named numbers . Notice the line,

Here, the keySet() method returns a set view of all the keys . The variable key access each key from the view.

Note : The Key of HashMap is of String type. Hence, we have used the String variable to access the keys.

Recommended Reading

  • HashMap entrySet() - returns set view of all mappings (entries)
  • HashMap values() - returns set view of all values

Sorry about that.

Related Library Functions

Java Library

Java: How to Get Keys and Values from a Map

set string keys = map keyset()

  • Introduction

Key-value stores are essential and often used, especially in operations that require fast and frequent lookups. They allow an object - the key - to be mapped to another object, the value. This way, the values can easily be retrieved, by looking up the key.

In Java, the most popular Map implementation is the HashMap class. Aside from key-value mapping, it's used in code that requires frequest insertions, updates and lookups. The insert and lookup time is a constant O(1).

In this tutorial, we'll go over how to get the Keys and Values of a map in Java .

  • Get Keys and Values (Entries) from Java Map

Most of the time, you're storing key-value pairs because both pieces of info are important. Thus, in most cases, you'll want to get the key-value pair together.

The entrySet() method returns a set of Map.Entry<K, V> objects that reside in the map. You can easily iterate over this set to get the keys and their associated values from a map.

Let's populate a HashMap with some values:

Now, let's iterate over this map, by going over each Map.Entry<K,V> in the entrySet() , and extracing the key and value from each of those entries:

This results in:

  • Get Keys and Values (Entries) from Java Map with forEach()

Java 8 introduces us to the forEach() method for collections. It accepts a BiConsumer<? super K, ? super V> action . The forEach() method performs the given BiConsumer action on each entry of the HashMap .

Let's use the same map from before, but this time, add a year to each of the entries' ages:

This prints out:

Or, instead of consuming each key and value from the map, you can use a regular Consumer and just consume entire entries from the entrySet() :

This also results in:

  • Get Keys from a Java Map

To retrieve just keys, if you don't really need any information from the values, instead of the entry set, you can get the key set:

  • Get Values from a Java Map

Similarly, one may desire to retrieve and iterate through the values only, without the keys. For this, we can use values() :

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

  • Check if Map Contains a Key

The HashMap class has a containsKey() method, which checks if the passed key exists in the HashMap , and returns a boolean value signifying the presence of the element or lack thereof.

Let's check if a key, 5 exists:

And for an existing key:

In this article, we've gone over a few ways to get keys and values (entries) of a Map in Java. We've covered using an iterator and going through each Map.Entry<K, V> , as well as using a forEach() method both on the map itself, as well as its entry set.

Finally, we've gone over how to get the key set and values separately, and check if a map contains a given key.

You might also like...

  • Java: Finding Duplicate Elements in a Stream
  • Spring Boot with Redis: HashOperations CRUD Functionality
  • Spring Cloud: Hystrix
  • Java Regular Expressions - How to Validate Emails

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

In this article

Make clarity from data - quickly learn data visualization with python.

Learn the landscape of Data Visualization tools in Python - work with Seaborn , Plotly , and Bokeh , and excel in Matplotlib !

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013- 2023 Stack Abuse. All rights reserved.

  • All Articles List
  • 23 November 2021

How to use keySet method in java.util.Map

Hashmap keyset() method signature and operating principle, hashmap keyset() examples.

HowToDoInJava

Java – Convert a Map to Array, List or Set

January 11, 2023

This Java tutorial will teach how to convert Map keys and values to the array, List or Set . Java maps are a collection of key-value pairs. The Map keys are always unique but can have duplicate values .

1. Convert Map to Array

For demo purposes, let us create a Map with String keys and Integer values.

The Map.values() returns a collection view of the values contained in this map. Use Collection.toArray() to get the array from collection elements. This method takes the runtime type of the returned array.

Similarly, we can collect the Map keys into an array . Map.keyset() returns the Set of all the keys in a Map . Using Set.toArray() we can convert it to an array of Strings.

2. Convert Map to List

We can collect the Map values into a List using the ArrayList constructor which takes a collection of values as its parameter.

We can use Java Streams to achieve the same result.

Likewise, we can convert Map keys to List using plain Java and Streams.

3. Convert Map to Set

We can use the HashSet constructor or Streams to convert Map values to a Set .

The Map.keySet() returns a Set view of all the keys in the Map .

4. Conclusion

This tutorial taught us how to convert Java Map keys and values into an Array, List or Set with simple examples. We learned to use the ArrayList and HashSet constructors as well as Stream APIs.

Happy Learning!!

Discover More

Related Articles And Resources

guest

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Tutorial Series

Privacy Policy

REST API Tutorial

Ace your Coding Interview

  • DSA Problems
  • Binary Tree
  • Binary Search Tree
  • Dynamic Programming
  • Divide and Conquer
  • Linked List
  • Backtracking

Iterate Map in Java using keySet() method

This post will discuss various methods to iterate map using keySet() in Java.

We know that the keySet() method returns a set view of the keys contained in the map. So, we can iterate a map using keySet() and for each key calling map.get(key) to fetch a value. There are several ways to do that:

1. Using Iterator

Since the map doesn’t extend the Collection interface, it doesn’t have its own iterator. Since Set extends the Collection interface, we can get an iterator to set of keys returned by keySet() . Now we can easily process each key by using a simple while loop, as shown below:

2. Using for-each loop (Enhanced for statement)

The for-loop also has another variation designed for iteration through collections and arrays. It is called a for-each loop and is available to any object implementing the Iterable interface. As Set extends the Collection interface, and Collection extends Iterable interface, we can use a for-each loop to loop through the keySet. Please note that this approach will also invoke the iterator() method behind the scenes.

3. Using Iterator.forEachRemaining() method

We can also use the forEachRemaining() method that is the latest addition to the Iterator interface in Java 8 and above. It performs the given action for each remaining element until all elements have been processed.

4. Using Stream.forEach() method

We can use streams in Java 8 and above to iterate a map by passing the lambda expression to the forEach() method of the Stream interface that performs an action for each element of this stream.

5. Using Stream.of() + toArray() + forEach() method

We can also call forEach operation on stream of objects returned by Stream.of() method:

    Following is a simple Java program that covers all approaches discussed above:

Download    Run Code

  We can also use generics for Iterator and for-each loop method discussed above:

That’s all about iterating over a Map in Java using the keySet() method.

  Related Post:

Iterate Map in Java using the entrySet() method

Rate this post

Average rating 5 /5. Vote count: 14

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and support our growth. Happy coding :)

set string keys = map keyset()

Software Engineer | Content Writer | 12+ years experience

guest

IMAGES

  1. hashmap keyset : java map keyset and keyset java

    set string keys = map keyset()

  2. Map中的keySet()的坑

    set string keys = map keyset()

  3. Java

    set string keys = map keyset()

  4. Map集合遍历的三种方式-IT Blog

    set string keys = map keyset()

  5. Solved: Write Output Printed Given Method Passed Following

    set string keys = map keyset()

  6. Map中keySet和entrySet区别_keyset遍历map为什么会慢-CSDN博客

    set string keys = map keyset()

VIDEO

  1. Keys no locks

  2. L Tuesday..✌️key oo 🗝️ set ..🤑 Dangerous POSITION Lapping has set 💯..fire 4 fire .20/6/23

  3. Design of Keys

  4. Guardian Of The Keys

  5. The Black Keys

  6. [NEET 2018] Answer key

COMMENTS

  1. java

    9 Answers Sorted by: 5 Use: Set<MyGenericType> keySet = map.keySet (); Always try to specify the Interface type for collections returned by these methods. This way regardless of the actual implementation class of the Set returned by these methods (in your case map.keySet ()) you would be ok.

  2. Map keySet() Method in Java with Examples

    Syntax: Set keySet () Parameters: This method has no argument. Returns: This method returns a set containing keys of the specified map. Below programs show the implementation of int keySet () method. Program 1: import java.util.*; public class GfG { public static void main (String [] args) { Map<String, String> map = new HashMap<> ();

  3. HashMap keySet() Method in Java

    Syntax: hash_map.keySet () Parameters: The method does not take any parameter. Return Value: The method returns a set having the keys of the hash map. Below programs are used to illustrate the working of java.util.HashMap.keySet () Method: Program 1: Mapping String Values to Integer Keys. import java.util.*; public class Hash_Map_Demo {

  4. Java Map

    The keySet () method returns the Set of keys contained in the Map. Let's apply the method keySet () to the Map and store it in a Set variable actualValues: Set<String> actualValues = map.keySet (); Now, let's confirm that the size of the returned Set is 2: assertEquals ( 2, actualValues.size ());

  5. Java HashMap keySet()

    The syntax of the keySet () method is: hashmap.keySet () Here, hashmap is an object of the HashMap class. keySet () Parameters The keySet () method does not take any parameter. keySet () Return Value returns a set view of all the keys of the hashmap Note: The set view only shows all keys of the hashmap as a set.

  6. Java initialize map with keys from set

    In java, can you initialize a new map's keyset based on the values of an existing set? Something like: Set<String> setOfStrings = getSetFromSomeOtherFuntion (); Map<String, Boolean> map = new Hashmap<> (setOfStrings);

  7. Java: How to Get Keys and Values from a Map

    To retrieve just keys, if you don't really need any information from the values, instead of the entry set, you can get the key set: for (String key: map.keySet ()) { System.out.println (key); } Output: Billy David John Jane

  8. How to use keySet method in java.util.Map

    Set<K> keySet () method returns a Set view of the keys that are contained in this map. The feature of this Set collection, that keeps the keys, is that there cannot be duplicate elements in it. The set is backed by the map. That means that if something was changed in the map, it is reflected in the set, and vice-versa.

  9. java collections

    I put a string array elements is a map where elements of string array is key and frequency of word is value, e.g.: String [] args = {"if","it","is","to","be","it","is","up","me","to","delegate"}; then the map will have entries like [ if:1, it:2 .... ] Set<String> keys = m.keySet (); System.out.println ("keyset of the map : "+keys);

  10. data structures

    This is doable, at least in theory, if you know the index: System.out.println(team1.keySet().toArray()[0]); keySet() returns a set, so you convert the set to an array. The problem, of course, is that a set doesn't promise to keep your order.

  11. Using keySet() method then changing the Set to a String Array? Java

    1 Answer Sorted by: 61 You can do Map<String, Object> map = ... String [] strings = map.keySet ().toArray (new String [map.size ()]); This works for any kind of map, including TreeMap Share Improve this answer Follow

  12. Hashmap methods in Java with Examples

    keySet (): java.util.HashMap.keySet () It returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. Syntax: public Set keySet () Return: a set view of the keys contained in this map

  13. Map interface keySet(), values(), entrySet() methods in Java

    The keySet () method returns a Set view of the keys contained in the Map. The method does not take any parameters and has a return type Set<K>, where K is the type of keys in the Map. The values () method returns a Collection view of the values contained in the Map.

  14. Java

    Java HashMap Collection Conversion, Java Map This Java tutorial will teach how to convert Map keys and values to the array, List or Set. Java maps are a collection of key-value pairs. The Map keys are always unique but can have duplicate values. 1. Convert Map to Array For demo purposes, let us create a Map with String keys and Integer values.

  15. Convert Map with Set of Strings as key to Map with Strings (Java)

    Java 8-11. Map<Set<String>, User> --> Map<String, User> Imagine, that elements inside of the set are won't repeat. One more note: many unique keys can point to the same value. I made this with the following code: Map<String, User> result = new HashMap<> (); existingMap.forEach ( (set, user) -> set.forEach (item -> result.put (set, user)));

  16. Remove multiple keys from Map in efficient way?

    Assuming your set contains the strings you want to remove, you can use the keySet method and map.keySet().removeAll(keySet);. keySet returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. Contrived example:

  17. Iterate Map in Java using keySet() method

    This post will discuss various methods to iterate map using keySet () in Java. We know that the keySet () method returns a set view of the keys contained in the map. So, we can iterate a map using keySet () and for each key calling map.get (key) to fetch a value. There are several ways to do that: 1. Using Iterator.

  18. How can I find a key in a map based on a pattern matching in java?

    You can grab the keySet of the map and then filter to get only keys that starts with "address" and add the valid keys to a new Set. With Java 8, it's a bit less verbose: Set<String> set = map.keySet () .stream () .filter (s -> s.startsWith ("address")) .collect (Collectors.toSet ()); Share Improve this answer

  19. how can I get a std::set of keys to a std::map

    What you basically want is a copy, as std::map doesn't keep the keys in a std::set. std::copy assumes that the value types are compatible, which isn't the case here. The std::map::value_type is a std::pair. You want to copy only the first part of the pair, which means you need a std::transform. Now, since you will be using an insert_iterator on ...

  20. Java HashMap keySet() 方法

    Java HashMap keySet () 方法返回映射中所有 key 组成的 Set 视图。 keySet () 方法的语法为: hashmap.keySet () 注: hashmap 是 HashMap 类的一个对象。 参数说明: 无 返回值 返回映射中所有 key 组成的 Set 视图。 实例 以下实例演示了 keySet () 方法的使用: 实例 import java.util.HashMap; class Main { public static void main (String[] args) { // 创建一个 HashMap HashMap <Integer, String > sites = new HashMap <>(); // 往 HashMap 添加一些元素

  21. TreeMap keySet() Method in Java with Examples

    In Java, keySet() method of TreeMap class is present inside java.util package in Java is used to create a set out of the key elements contained in the treemap. It basically returns a set view of the keys or we can create a new set and store the key elements in them in ascending order. Since the set is backed by the map, any changes made to the map are reflected in the set, and vice-versa.