views:

93

answers:

2

My data has been placed into an array, but unfortunately not in the order I want it in...

String[][] databaseToArray = {
  //{"Name", "Channel", "Description", "Amount", "isReady"},
    {"John", "Nick",    "likes",       "2",      "yes"    },
    {"Drew", "MTV",     "dislikes",    "4",      "no"     },
    {"Fred", "CNN",     "okay",        "3",      "no"     },
    {"Beth", "Fox",     "valid",       "1",      "yes"    }
};

How do I manipulate this array so that when I loop through it the order is by the amount , similar to SELECT * FROM "databaseToArray" ORDER BY "Amount" aka

String[][] reorganizedArray = {
  //{"Name", "Channel", "Description", "Amount", "isReady"},
    {"Beth", "Fox",     "valid",       "1",      "yes"    },
    {"John", "Nick",    "likes",       "2",      "yes"    },
    {"Fred", "CNN",     "okay",        "3",      "no"     },
    {"Drew", "MTV",     "dislikes",    "4",      "no"     }
};
A: 

I found the sort method on the processing website, but this is only for One-Dimensional Arrays...

http://processing.org/reference/sort_.html

   float[] a = { 3, 5, 2, 4, 1 };
   a = sort(a);
   println(a);
// Prints 1, 2, 3, 4, 5
jonobr1
+2  A: 

You'll want to pass a Comparator to the Arrays.sort method. I haven't done Java in 5 years, but it should be easily doable. Maybe someone can clean up this example I'm about to write, since I'm pretty certain I'll get something wrong.

String[][] databaseToArray = {
  //{"Name", "Channel", "Description", "Amount", "isReady"},
    {"John", "Nick",    "likes",       "2",      "yes"    },
    {"Drew", "MTV",     "dislikes",    "4",      "no"     },
    {"Fred", "CNN",     "okay",        "3",      "no"     },
    {"Beth", "Fox",     "valid",       "1",      "yes"    }
};

Arrays.sort(databaseToArray, new Comparator<String[]>() {
    public int compare(String[] a, String[] b) {
        return a[3].compareTo(b[3]);
    }
});
TheSoftwareJedi