Jon Jon - 4 months ago 9
Java Question

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!

Answer

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());
   }
});
Comments