Is there a simple way to alphabetize a String Enumeration in Java?

你说的曾经没有我的故事 提交于 2019-12-24 03:40:12

问题


Just as the title says.

I tried messing around a bit with Collections.sort() on a List[] and the .sort() function of an ArrayList but I was never able to parse it back to an Enumeration.

Thanks!

EDIT:

Here's some pseduocode and further explanation. My goal is to take the keys() from a Hashtable and do complex operations involving each one, alphabetically.

My current process is:

  1. Take a hash table I'm given
  2. Form an enumeration from the ht
  3. Run a while loop until the enumeration is empty

So the code is like this:

public void processData(Hashtable<String,GenericClass> htData)
{
    Enumeration<String> enData = htData.keys();

    while(enData.hasMoreElements())
    {
        String current = enData.nextElement();

        /*
         * DO COMPLEX PROCESS
         */
    }
}

The problem, is that the data in the enumeration has to be alphabetical (that is, the "complex process" must be done on each key in alphabetical order). Any solutions? Thanks!


回答1:


If you have a sorted list you can use

Collections.enumeration(myList)

to get it back to an enumeration... if I'm following you correctly..

EDIT:

You can do this...

List l = new ArrayList(ht.keySet());
Collections.sort(l)



回答2:


If you need to iterate over the items in order of their keys, maybe it's better to use a TreeMap instead of a Hashtable. Its keySet method will return the keys in order.




回答3:


What about storing your keys in an ArrayList to sort them?

    List<String> list = // create from htData.keys()
    Collections.sort(list);
    for(String s : list) {
    ...



回答4:


Following should work:

Enumeration<String> enumeration = dictionary.keys(); // unsorted enumeration        
List list= Collections.list(enumeration); // create list from enumeration 
Collections.sort(list);
enumeration = Collections.enumeration(list);


来源:https://stackoverflow.com/questions/1498615/is-there-a-simple-way-to-alphabetize-a-string-enumeration-in-java

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