Java - How to sort with Comparator, the difference from Comparable

You can create a Comparator object to sort Collections, arrays, etc.

Comparators can be created in two ways:

  1. Anonymous class
  2. Lambda Expressions

Create Comparator with anonymous class

You can create a Comparator with an anonymous class. The return value of compare() can be negative, positive, or zero. If a negative number is returned, the right argument is moved down.

public void comparatorExample1() {
    List<String> strings = new ArrayList<>();
    strings.add("This code is free software");
    strings.add("you can redistribute it");
    strings.add("under the terms of the GNU General Public License version 2 only");
    strings.add("This code is distributed in the hope that it will be useful");
    strings.add("Please contact Oracle");
    strings.add("500 Oracle Parkway, Redwood Shores, CA 94065 USA");

    // before sorting
    for (String str : strings) {
        System.out.println(str);
    }

    // sorting by character length (ascending order)
    Collections.sort(strings, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.length() - s2.length();
        }
    });

    // out after sorting
    System.out.println();
    for (String str : strings) {
        System.out.println(str);
    }
}

result

This code is free software
you can redistribute it
under the terms of the GNU General Public License version 2 only
This code is distributed in the hope that it will be useful
Please contact Oracle
500 Oracle Parkway, Redwood Shores, CA 94065 USA

Please contact Oracle
you can redistribute it
This code is free software
500 Oracle Parkway, Redwood Shores, CA 94065 USA
This code is distributed in the hope that it will be useful
under the terms of the GNU General Public License version 2 only

Create Comparator with Lambda Expression

Anonymous classes can also be expressed as lambda expressions.

public void comparatorExample2() {
    List<String> strings = new ArrayList<>();
    strings.add("This code is free software");
    strings.add("you can redistribute it");
    strings.add("under the terms of the GNU General Public License version 2 only");
    strings.add("This code is distributed in the hope that it will be useful");
    strings.add("Please contact Oracle");
    strings.add("500 Oracle Parkway, Redwood Shores, CA 94065 USA");

    // before sorting
    for (String str : strings) {
        System.out.println(str);
    }

    // sorting by character length (ascending order)
    Collections.sort(strings, (s1, s2) -> s1.length() - s2.length());

    // out after sorting
    System.out.println();
    for (String str : strings) {
        System.out.println(str);
    }
}

result

This code is free software
you can redistribute it
under the terms of the GNU General Public License version 2 only
This code is distributed in the hope that it will be useful
Please contact Oracle
500 Oracle Parkway, Redwood Shores, CA 94065 USA

Please contact Oracle
you can redistribute it
This code is free software
500 Oracle Parkway, Redwood Shores, CA 94065 USA
This code is distributed in the hope that it will be useful
under the terms of the GNU General Public License version 2 only

Differences from Comparables

Comparable is an interface, and if a class implements this interface, it can be used to sort a list, etc.

public interface Comparable<T> {
    public int compareTo(T o);
}

Comparable as You can create a class that implements . Just override the compareTo() method and implement the code that compares two objects (this and its argument).

public class Text implements Comparable<Text> {
    private String mText;

    public Text(String text) {
        mText = text;
    }

    public String getText() {
        return mText;
    }

    @Override
    public int compareTo(@NotNull Text right) {
        return getText().length() - right.getText().length();
    }
}

And you can sort by calling Collections.sort() like this:

public void comparableExample1() {
    List<Text> texts = new ArrayList<>();
    texts.add(new Text("This code is free software"));
    texts.add(new Text("you can redistribute it"));
    texts.add(new Text("under the terms of the GNU General Public License version 2 only"));
    texts.add(new Text("This code is distributed in the hope that it will be useful"));
    texts.add(new Text("Please contact Oracle"));
    texts.add(new Text("500 Oracle Parkway, Redwood Shores, CA 94065 USA"));

    // before sorting
    for (Text text : texts) {
        System.out.println(text.getText());
    }

    // sorting by character length (ascending order)
    Collections.sort(texts);

    // out after sorting
    System.out.println();
    for (Text text : texts) {
        System.out.println(text.getText());
    }
}

For more details, refer to Java - How to Sort with Comparator.

codechachaCopyright ©2019 codechacha