Over a million developers have joined DZone.

Java Comparator Interface

DZone's Guide to

Java Comparator Interface

Free Resource
// 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;


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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


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

{{ parent.tldr }}

{{ parent.urlSource.name }}