Sort an ArrayList<String[]> by name in Java
The ArrayList<String[]> is inserted as follows
Apple | NY | A1 |
Carrots | SF | C2 |
Banana | SEA | B3 |
Sort the first column so
Apple | NY | A1 |
Banana | SEA | B3 |
Carrots | SF | C2 |
/******* ArrayListStringArrayDemo.java ******/
import java.util.ArrayList;
public class ArrayListStringArrayDemo {
public static void main(String[] args) {
// Creating ArrayList Which
holds String Arrays
ArrayList<String[]> arl = new
ArrayList<String[]>();
String s1[] = { "Apple", "Carrots",
"Banana" };
String s2[] = { "NY", "SF",
"SEA" };
// Adding arrays to the
ArrayList
arl.add(s1);
arl.add(s2);
String temp;
// Displaying the arrays in the
arraylist
System.out.println("_______ Before
Sorting ______");
for (int i = 0; i <
arl.get(0).length; i++) {
System.out.printf("%-30s%s\n", arl.get(0)[i], arl.get(1)[i]);
}
// This Logic will Sort the
ArrayList of Arrays of elements in Ascending
// order
for (int h = 0; h < arl.size();
h++) {
for (int i =
0; i < arl.get(h).length; i++) {
for (int j = i + 1; j < arl.get(h).length;
j++) {
if
(arl.get(h)[i].compareTo(arl.get(h)[j]) > 0) {
temp =
arl.get(h)[i];
arl.get(h)[i] = arl.get(h)[j];
arl.get(h)[j] = temp;
}
}
}
}
// Displaying the arrays in the
arraylist
System.out.println("_______ After
Sorting ______");
for (int i = 0; i <
arl.get(0).length; i++) {
System.out.printf("%-30s%s\n", arl.get(0)[i], arl.get(1)[i]);
}
}
}
/****************************************************/
/****************************************************/
Output:
/****************************************************/
Get Answers For Free
Most questions answered within 1 hours.