Date: 2010aug7
Update: 2026mar18
Language: java
Keywords: Comparable
Q. Java: Sort an ArrayList without modifying the class in the ArrayList
A. Use the custom compare option for Collections.sort().
Here is a full example:
import java.util.Collections;
import java.util.Comparator;
import java.util.ArrayList;
class Demo {
static class MyEntry {
public String field1;
public String field2;
MyEntry(String field1In, String field2In) {
field1 = field1In;
field2 = field2In;
}
@Override
public String toString() {
return "{" + field1 + "," + field2 + "}";
}
};
static class CustomCompare implements Comparator<MyEntry> {
@Override
public int compare(MyEntry a, MyEntry b) {
return a.field1.compareTo(b.field1);
}
}
public static final void main(String[] args) {
var a = new ArrayList<MyEntry>();
// Add things to a
a.add(new MyEntry("ONE", "one"));
a.add(new MyEntry("TWO", "two"));
a.add(new MyEntry("THREE", "three"));
// ...
// Sort using our custom function
Collections.sort(a, new CustomCompare());
// Its now sorted and we didn't have to modify the MyEntry class
// Output
for (int i = 0; i < a.size(); i++) {
System.out.println("a[" + i + "]=" + a.get(i).toString());
}
}
}
Output:
a[0]={ONE,one}
a[1]={THREE,three}
a[2]={TWO,two}