문제

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"     }
};
도움이 되었습니까?

해결책

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]);
    }
});

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top