Jon
Jon

Reputation: 150

Sorting An Array of Pairs By The First Value in Java

I have a simple pair class and have created an array of them.

private static class Pair
{
    private String l;
    private String e;
}

I was wondering if it's possible to sort an array of pairs such as: (a, de), (g, e), (dde, gh) by just first element in the pair. Creating a result of: (a, de), (dde, gh), (g,e) I know this is possible in c++, but I'm new to Java and have been searching online for hours for a solution. I've read that you can use Comparator, but am still not sure how that really works. Any suggestions would be very much appreciated. Thanks!

Upvotes: 0

Views: 13071

Answers (3)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

Using an inline custom comparator:

Arrays.sort(pairArray, new Comparator<Pair>() {
   @Override
   public int compare(Pair p1, Pair p2) {
       return p1.getL().compareTo(p2.getL());
   }
});

Upvotes: 3

Ruslan Batdalov
Ruslan Batdalov

Reputation: 793

In addition to Tim Biegeleisen's answer, there is one more option: make Pair implement Comparable interface:

private static class Pair implements Comparable<Pair>
{
    private String l;
    private String e;

    int compareTo(Pair that) {
        return this.l.compareTo(that.l);
    }
}

List<Pair> pairList;
Collections.sort(pairList);

The choice between these two options depends on whether you want to modify Pair (Comparable requires it, Comparator does not), and whether you can have different possible orderings (Comparable allows to use only one ordering, Comparator allows to define as many orderings as you wish). Of course, you can also combine the approaches and implement default ordering in implementation of Comparable interface, but use also additional orderings with Comparator.

Upvotes: 1

Andrew Lygin
Andrew Lygin

Reputation: 6197

The general approach would be:

Arrays.sort(myArray, new Comparator<Pair>() {
    @Override
    public int compare(Pair p1, Pair p2) {
        return p1.l.compareTo(p2.l);
    }
});

Java 8 makes it simpler with lambdas:

Arrays.sort(myArray, (p1, p2) -> p1.l.compareTo(p2.l));

Upvotes: 2

Related Questions