Bradie
Bradie

Reputation: 85

2 dimensional array sorting by input then second

It's probably a rather basic question but I can't seem to find an answer that I require online.

However, what's the best way to sort a 2 dimensional array?

I have a pre-populated 2 dimensional array 'mainArr[][]' that contains data:

John Doe - 678DGHJ,Sport
Lisa Parker - 432KH3,Car
John Doe - 678DGHJ, Drive
Peter Bear 4HJ4K3,Bus
John Doe - 4HJK4,Loose

The comma being the separator between the dimension in the array. How can I sort it first by the column first in the array, then by the value in the second part of the array.

The sorted data above would become:

John Doe - 4HJK4,Loose
John Doe - 678DGHJ,Drive
John Doe - 678DGHJ,Sport
Lisa Parker - 432KH3,Car
Peter Bear 4HJ4K3,Bus

So the sorted data in the array of

mainArr[0][0] 

would equal

mainArr[John Doe - 4HJK4][Loose]

Upvotes: 0

Views: 70

Answers (1)

Sandeepa
Sandeepa

Reputation: 3755

You can use the Comparator like below to sort your array,

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String args[]) {
        String[][] mainArr = new String[][] {{"John Doe - 678DGHJ", "Sport"}, {"Lisa Parker - 432KH3", "Car"}, {"John Doe - 678DGHJ", "Drive"}, {"Peter Bear 4HJ4K3", "Bus"}, {"John Doe - 4HJK4", "Loose"}};

        Arrays.sort(mainArr, new Comparator<String[]>() {
            @Override
            public int compare(String[] entry1, String[] entry2) {
                if (entry1[0].equals(entry2[0])) {
                    return entry1[1].compareTo(entry2[1]);
                }
                return entry1[0].compareTo(entry2[0]);
            }
        });

        for (int i = 0; i < mainArr.length; i++) {
            System.out.println(mainArr[i][0] + ", " + mainArr[i][1]);
        }
    }

Upvotes: 2

Related Questions