按 XML 文件中项目的顺序对 Java 列表/映射进行排序
我想做的是按照 XML 文件中项目的顺序对 Java 列表或映射进行排序。
例如,
我有一个函数名称列表,如下所示:
- functionOne
- functionThree
- functionTwo
XML 文件如下所示:
<xml>
<function>functionOne</function>
<function>functionTwo</function>
<function>functionThree</function>
</xml>
所以我想对列表进行排序,以便函数名称如下所示:
- functionOne
- functionTwo
- functionThree
现在我尝试对变量执行此操作嗯,大约有 500 多个独特的“物品”。
有谁知道我该怎么做?现在,对于确定排序顺序的文件来说,它不必是 XML,它只是我最常用的文件,它可以是任何可以完成工作的文件。
预先感谢您的宝贵时间。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,解析 XML 文件以构建一个
Map
,它将名称映射到其顺序位置。然后,您需要一个自定义比较器:
然后将其应用到变量名称列表:
可能需要处理一些边缘情况,但这是一般想法。
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:
then apply it to your list of variable names:
There's probably some edge cases to take care of, but that's the general idea.
我只想使用 XML 解析器按顺序将 XML 文件中的值读取到
List
中,而不是采用不同的List
并根据它们的顺序对其进行排序在 XML 文件中找到。这是假设您正在谈论的排序的List
将包含在 XML 文件中找到的所有值。如果它可能只包含 XML 文件中值的子集,一种选择是首先从 XML 中读取所有值,然后使用 Guava 的 Ordering.explicit(List):
I would just use an XML parser to read the values from the XML file into a
List
in order rather than taking a differentList
and sorting it according to the order they're found in the XML file. This is assuming that theList
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):