Search code examples
javaxmlsortingbusiness-logicbusiness-rules

Sort Java List/Map by order in which items are in an XML File


What I'm looking to do is to sorta a Java List or Map in the order the items are in a XML File.

For Example

I have a list of function names as so:

  1. functionOne
  2. functionThree
  3. functionTwo

The XML File looks like this:

<xml>
  <function>functionOne</function>
  <function>functionTwo</function>
  <function>functionThree</function>
</xml>

So I would like to sort the list so the function names are as so:

  1. functionOne
  2. functionTwo
  3. functionThree

Now Im trying to do this for Variables as well, so there are around 500+ unique 'items'.

Does anyone have any idea how I can go about doing this? Now for the file that determines that sort order doesn't have to be XML it just what I use the most, it can be anything that can get the job done.

Thanks in advance for your time.


Solution

  • First, parse the XML file to build a Map<String,Integer> which maps the names to their ordinal position.

    Then, you need a custom Comparator:

    public class XMLComparator implements Comparator<String> {
        private Map<String,Integer> order;
    
        public XMLComparator(Map<String,Integer> desiredOrder) {
            order = desiredOrder;
        }
    
        public void compare(String s1, String s2) {
            return order.get(s1) - order.get(s2);
        }
    
    }
    

    then apply it to your list of variable names:

    Collections.sort(variableNames, new XMLComparator(previouslyCreatedMap));
    

    There's probably some edge cases to take care of, but that's the general idea.