我正在开发一款应用。我希望对ArrayList
进行排序。我面临的问题是,每当我有重复的条目时,排序都会失败并且应用程序崩溃。
截至目前的布局是:
虽然我希望以下列方式得到结果:
我已编写以下代码进行排序。
private void sortAlphaNumeric() {
/* Take a temporary list to store the original list */
/*
* Remove any white spaces in the question number as it might
* interfere in sorting
*/
String[] trimmedArray = new String[m_quesNumber.size()];
for (int i = 0; i < m_quesNumber.size(); i++) {
trimmedArray[i] = m_quesNumber.get(i).replace(" ", "");
}
m_quesNumber = new ArrayList<String>();
for (int i = 0; i < trimmedArray.length; i++) {
m_quesNumber.add(trimmedArray[i]);
}
ArrayList<String> temp_quesNumber = new ArrayList<String>(
m_quesNumber);
/* Sort the original list */
Collections.sort(m_quesNumber, new AlphanumComparator());
/* Temporary arrays */
String[] temp_prevQuesId = new String[m_quesId.size()];
String[] temp_quesMaxMarks = new String[m_quesMaxScore.size()];
Integer[] temp_quesOptional = new Integer[m_quesOptional.size()];
for (int i = 0; i < m_quesNumber.size(); i++) {
int old_position = temp_quesNumber.indexOf(m_quesNumber.get(i));
temp_prevQuesId[i] = m_quesId.get(old_position);
temp_quesMaxMarks[i] = m_quesMaxScore.get(old_position);
temp_quesOptional[i] = m_quesOptional.get(old_position);
}
m_quesId = new ArrayList<String>();
m_quesMaxScore = new ArrayList<String>();
m_quesOptional = new ArrayList<Integer>();
for (int i = 0; i < temp_prevQuesId.length; i++) {
m_quesId.add(temp_prevQuesId[i]);
m_quesMaxScore.add(temp_quesMaxMarks[i]);
m_quesOptional.add(temp_quesOptional[i]);
}
}
答案 0 :(得分:1)
制作一个类似......的模型类。
class Result {
String qNo;
int marksScored;
int maximumMarks;
...
}
并将Result
的arrayList设为
List<Result> results = new ArrayList<>();
添加所需数据,然后按照给定代码对其进行排序。
Collections.sort(results, new Comparator<Result>() {
@Override
public int compare(Result lhs, Result rhs) {
return lhs.qNo.compareToIgnoreCase(rhs.qNo);
}
});
答案 1 :(得分:0)
只需使用此代码而不是所有代码。
ArrayList<ArrayList<String>> data; //then initialize it
// and pass it here. Sort based on column 0
Collections.sort(data, new Comparator<ArrayList<String>>() {
@Override
public int compare(ArrayList<String> row1, ArrayList<String> row2) {
return row1.get(0).compareTo(row2.get(0));
}
});