Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an Enumeration (for the Keys) of a Map (HashMap) in Java?

Tags:

As far as I understand this, it seems that there is not a direct way of getting an Enumeration directly for the Keys of a HashMap. I can only get a keySet(). From that Set, I can get an Iterator but an Iterator seems to be something different than an Enumeration.

What is the best and most performant way to directly get an Enumeration from the Keys of a HashMap?

Background: I am implementing my own ResourceBundle (=>getKeys() Method), and I have to provide/implement a method that returns the Enumeration of all Keys. But my implementation is based on a HashMap so I need to somehow figure out how to best convert betweens these two "Iterator/Enumerator" techniques.

like image 561
tim Avatar asked Jan 12 '10 10:01

tim


People also ask

How do I get a list of map keys?

To retrieve the set of keys from HashMap, use the keyset() method. However, for set of values, use the values() method.

Can we have enum as key in HashMap?

In HashMap, we can use Enum as well as any other object as a key.

How do you get all keys of a map as a list in Java?

Use keySet() to Get a Set of Keys From a HashMap in Java The simplest way to get the keys from a HashMap in Java is to invoke the keySet() method on your HashMap object. It returns a set containing all the keys from the HashMap .


1 Answers

I think you can use the method enumeration from java.util.Collections class to achieve what you want.

The API doc of the method enumerate has this to say:

public static Enumeration enumeration(Collection c)
Returns an enumeration over the specified collection. This provides interoperability with legacy APIs that require an enumeration as input.

For example, the below code snippet gets an instance of Enumeration from the keyset of HashMap

 final Map <String,Integer> test = new HashMap<String,Integer>();  test.put("one",1);  test.put("two",2);  test.put("three",3);  final Enumeration<String> strEnum = Collections.enumeration(test.keySet());  while(strEnum.hasMoreElements()) {      System.out.println(strEnum.nextElement());  } 

and resulting the output is:
one
two
three

like image 71
sateesh Avatar answered Oct 06 '22 01:10

sateesh