My code is as follows:
import java.util.ArrayList;
import java.util.Arrays; import java.util.List;
public class Sorting {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> theMenu = new ArrayList<String>();
String[] Array1 = {
"M1", "Wine", "2.50",
"M2", "Soft drink", "1.50",
"D1", "Fish", "7.95",
"D2", "Veg chili", "6.70"
};
theMenu.addAll(Arrays.asList(Array1));
String[] temp1 = new String[3];
String[] temp2 = new String[3];
for (int i = 0; i < theMenu.size(); i+=3) {
for (int j = i + 3; j < theMenu.size(); j+=3) {
if (i < theMenu.size() - 3) {
if (theMenu.get(i).compareTo(theMenu.get(i + 3)) > 0) {
temp1[0] = theMenu.get(i);
temp1[1] = theMenu.get(i + 1);
temp1[2] = theMenu.get(i + 2);
temp2[0] = theMenu.get(j);
temp2[1] = theMenu.get(j+1);
temp2[2] = theMenu.get(j+2);
theMenu.remove(j + 2);
theMenu.remove(j + 1);
theMenu.remove(j);
theMenu.remove(i + 2);
theMenu.remove(i + 1);
theMenu.remove(i);
theMenu.add(i, temp2[0]);
theMenu.add(i + 1, temp2[1]);
theMenu.add(i + 2, temp2[2]);
theMenu.add(j, temp1[0]);
theMenu.add(j + 1, temp1[1]);
theMenu.add(j + 2, temp1[2]);
}
}
}
}
System.out.println(theMenu);
}
}
I want to sort the ArrayList in the order D1, D2, M1, M2, M3, while keeping its respective items and price WITH the IDs. I am not allowed to change the storing method i.e make another class of Items with its own ID and name and price. How can I rearrange it so that it is in the form :
{"D1" , "Fish", "7.95"
"D2" , "Veg chili", "6.70",
"M1" , "Wine", "2.50",
"M2", "Soft drink", "1.50"
}
Inside the ArrayList. This should work regardless of how many items we store inn the arrayList. My code produces the following output:
[M1, Wine, 2.50, M2, Soft drink, 1.50, D1, Fish, 7.95, D2, Veg chili, 6.70]
Note: Forget the new lines in the array, I just need the indexes sorted out. Can anyone help me with this?