Sort Java List/Map by order in which items are in an XML File
-
12-10-2019 - |
Question
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:
- functionOne
- functionThree
- 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:
- functionOne
- functionTwo
- 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.
OTHER TIPS
I would just use an XML parser to read the values from the XML file into a List
in order rather than taking a different List
and sorting it according to the order they're found in the XML file. This is assuming that the List
you're talking about sorting would contain all the values that are found in the XML file.
If it might only contain a subset of the values in the XML file, one option would be to first read in all the values from the XML and then use Guava's Ordering.explicit(List):
Ordering<String> orderFromXml = Ordering.explicit(readListFromXml());
List<String> otherList = ...
Collections.sort(otherList, orderFromXml);