Over a million developers have joined DZone.

Java Comparator Interface

·
// A quick example of how to sort two objects using Java's Comparator interface.
// The call to Collections.sort uses an anonymous inner function to define
// the comparison between two objects.


    public String[] sortNodes(ArrayList nodes) {
        Node[] sortedNodes = new Node[nodes.size()];
        Collections.sort(nodes, new Comparator() {
            public int compare(Node o1, Node o2) {
                return o2.priority - o1.priority;
            }
        });
        for (int i=0; i < nodes.size(); i++) {
            sortedNodes [i] = nodes.get(i);
        }
        return sortedNodes ;
    }
    
class Node{
    public String name = null;
    public int priority;
}
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}