对一个 ArrayList<Node> 进行字典序排序?

3
我想对一个类型为Node的ArrayList进行排序,例如:
 [[country1: null], [name2: null], [city3: null], [region4: null], [name6: null]]

为了获取节点名称的值,我使用getNodeName()函数。
 ArrayNode.get(0).getNodeName()  // return country1

我一直在研究collection.sort,但不知道如何使用,提前感谢您的帮助。

Node类是什么样子的?你想按照它的哪个属性进行排序? - Philipp Reichart
不是一个*完全相同的复制,但非常接近于https://dev59.com/xnE85IYBdhLWcg3wbS1h - Corbin
3个回答

3

使用Comparator对象定义比较逻辑。

类似这样:

ArrayList<Node> nodes;
        Collections.sort(nodes, new Comparator<Node>() {
            @Override
            public int compare(Node o1, Node o2) {
                return o1.getNodeName().compareTo(o2.getNodeName());
            }
        });

3
我认为您需要使用java.util.Comparator。您可以将其与Collections.sort一起使用。

3
创建一个通过节点名称排序的Comparator,然后使用Collections.sort(list,comparator)进行排序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接