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

半腔热情 提交于 2019-12-02 22:23:53
Bozho

Apache commons-collections have an adapter that makes the Iterator available for use like an Enumeration. Take a look at IteratorEnumeration.

Adapter to make an Iterator instance appear to be an Enumeration instances

So in short you do the following:

Enumeration enumeration = new IteratorEnumeration(hashMap.keySet().iterator());

Alternatively, if you (for some reason) don't want to include commons-collections, you can implement this adapter yourself. It is easy - just make an implementation of Enumeration, pass the Iterator in a constructor, and whenever hasMoreElements() and nextElement() are called, you call the hasNext() and next() on the underlying Iterator.

Use this if you are forced to use Enumeration by some API contract (as I assume the case is). Otherwise use Iterator - it is the recommended option.

sateesh

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

You can write a adapter to adapt to Enumeration.

    public class MyEnumeration implements Enumeration {

        private Iterator iterator;

        public MyEnumeration(Iterator iterator){
            this.iterator = iterator;
        }


        public MyEnumeration(Map map) {
            iterator = map.keySet().iterator();
        }


        @Override
        public boolean hasMoreElements() {
            return iterator.hasNext();
        }


        @Override
        public Object nextElement() {
            return iterator.next();
        }

    }

And then you can use this custom enumeration :)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!