0

EDIT: I tried using a camparator and it didnt work, I get an error

I have to read in a file with the contents

2011 Regular Season
Boston 162 5710 875 1600 352 35 203
NY_Yankees 162 5518 867 1452 267 33 222
Texas 162 5659 855 1599 310 32 210
Detroit 162 5563 787 1540 297 34 169
St.Louis 162 5532 762 1513 308 22 162
Toronto 162 5559 743 1384 285 34 186
Cincinnati 162 5612 735 1438 264 19 183
Colorado 162 5544 735 1429 274 40 163
Arizona 162 5421 731 1357 293 37 172
Kansas_City 162 5672 730 1560 325 41 129

this is the code I read it in with

static String specstat[][] = new String[1000][1000];

public static void main(String args[]) {

Arrays.sort(specstat, new Comparator<String[]>() {
        @Override
        public int compare(final String[] entry1, final String[] entry2) {
            final String time1 = entry1[0];
            final String time2 = entry2[0];
            return time1.compareTo(time2);
        }
    });

    for (final String[] s : specstat) {
        System.out.println(s[0] + " " + s[0]);
    }


    execute();
}

public static String[][] execute() {
    int line = 0;
    try {
        BufferedReader in = new BufferedReader(new FileReader(
                "files/input.txt"));

        String str;
        while ((str = in.readLine()) != null) {
            if (str.trim().length() == 0) {
                continue; // Skip blank lines
            }
            specstat[line] = str.split("\\s+");
            line++;
        }
        in.close();
    } catch (IOException e) {
        System.out.println("Can not open or write to the file.");
    }
    return specstat;

}

How can I sort the 2D Array based off of the first column of the last (or any) column of numbers from the text file?

user222786
  • 547
  • 4
  • 7
  • 17
  • 1
    Any reason why you want to use arrays instead of some collection like a List of Maps? – fvu May 30 '13 at 16:50
  • @fvu whats a list of maps (the data is baseball stats)? – user222786 May 30 '13 at 16:52
  • 1
    I suggest that you create a class `Team` to store the data for a single team. Then make a 1D array of `Team` objects and sort it using a `Comparator` class. – Code-Apprentice May 30 '13 at 16:53
  • See also this [example](http://stackoverflow.com/a/5064357/230513). – trashgod May 30 '13 at 16:55
  • @user222786 see rgettman's answer, it's an elaboration of that idea (but rgettman uses classes for each "row", which is arguably an even better solution than using maps) – fvu May 30 '13 at 16:57

4 Answers4

3

I wouldn't use a 2D array for this purpose.

I would create a Team class and define instance variables for each of the fields in the file format. Then I would create a class that implements Comparator (say, TeamComparator) that defines how to compare Teams based on whatever criteria is needed.

Then, you can have an array of Teams or a List of Teams.

Last, you can sort the array with

Arrays.sort(teamsArray, new TeamComparator()) 

or the list with

Collections.sort(teamsList, new TeamComparator())
Anirudha
  • 32,393
  • 7
  • 68
  • 89
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • +1 Sounds familiar: http://stackoverflow.com/questions/16841748/sort-2d-array-in-java#comment24285154_16841748 – Code-Apprentice May 30 '13 at 16:54
  • @rgettman could you show an example of how to use teamcomparator – user222786 May 30 '13 at 17:00
  • Please read all about `Comparator`, using the link I provided in my answer -- specifically about how to implement the `compare` method in your `TeamComparator` class. – rgettman May 30 '13 at 17:05
3

From what I'm understanding, you want to sort the 2D array by arranging the positions of the arrays inside of them. You can use Arrays.sort() with a custom Comparator like this:

Arrays.sort(specstat, new Comparator<String[]>() {
    @Override
    public int compare(String[] array1, String[] array2) {
        //do your comparison here...
    }
});

It may help to use String.compare() or compare numerical values using Integer.parseInt(String s). If you want to sort the individual String arrays inside the 2D array, you'll have to sort each array individually.

EDIT: see the comments for a suggested compare method.

Shrike
  • 155
  • 9
  • How do you make a comparison, if I wanted to compare the last column of every row? – user222786 May 30 '13 at 17:05
  • The last entry in each array is a number. So, we'll need to get the numbers using `int num1 = Integer.parseInt(array1[array1.length - 1]);` and do the same thing for `num2` but instead using `array2`. You can then return `num1 - num2` if you want to sort in ascending order, or return `num2 - num1` if you want to sort in descending order. Be careful, though: `Integer.parseInt()` throws a `NumberFormatException` if it gets anything that isn't a number. Because of this, you may want to exclude the first String array when you sort. – Shrike May 30 '13 at 17:09
  • could you edit your answer please. It would be extremely helpful – user222786 May 30 '13 at 17:11
  • Yeah, I just fixed it. Sorry about that. – Shrike May 30 '13 at 17:11
  • I'm not sure what else to say. I've told you exactly how to compare the last entries in each array. – Shrike May 30 '13 at 17:16
  • THANKS! I got it to work... kind of, do you know how I can skip the first row/line of the array (the first row/line is 2011 regular season) – user222786 May 30 '13 at 17:28
  • Use `Arrays.sort(T[], int, int, java.util.Comparator)`, it takes two numbers which specify the range of the array to sort. You'll want to sort from `1` to `specstat.length`. – Shrike May 30 '13 at 17:31
0

Use QuickSort to sort your array

Jainendra
  • 24,713
  • 30
  • 122
  • 169
0

You can use Arrays.sort with a comparator.

nrainer
  • 2,542
  • 2
  • 23
  • 35