Array List Sorting [duplicate]
How would you sort an ArrayList
alphabetically or numerically? I am not really sure how a method sorting an array either alphabetically or numerically would work.
Thanks!
The Collections.sort methods allow one to sort a list with a Comparator that implements your particular sorting method (e.g. alphabetic or numeric sort).
[Collections.sort][1] will sort by default ordering. This is lexical (alphabetical) for strings and numerical for numeric data types. You can also specify your own comparator if you need non-standard ordering.
For example:
ArrayList list = new ArrayList();
list.add(1);
list.add(10);
list.add(-1);
list.add(5);
Collections.sort( list );
[1]: http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator)
Generally use Collections.sort()
method to sort a simple array list.
Here is an example.
First implement Comparable
interface and then Override the compareTo
method.
public class Student implements Comparable {
private String studentname;
private int rollno;
private int studentage;
public Student(int rollno, String studentname, int studentage) {
this.rollno = rollno;
this.studentname = studentname;
this.studentage = studentage;
}
@Override
public int compareTo(Student comparestu) {
int compareage=((Student)comparestu).getStudentage();
}
@Override
public String toString() {
return "[ rollno=" + rollno + ", name=" + studentname + ", age=" + studentage + "]";
}
}
Now we can very well call Collections.sort
on ArrayList
import java.util.*;
public class ArrayListSorting {
public static void main(String args[]){
ArrayList<Student> arraylist = new ArrayList<Student>();
arraylist.add(new Student(100, "Nuwan", 19));
arraylist.add(new Student(200, "Kamal", 18));
arraylist.add(new Student(205, "Sunil", 20));
Collections.sort(arraylist);
for(Student str: arraylist){
System.out.println(str);
}
}
}
Collections.sort(list,new Comparator() {
int compare(T o1, T o2) {
// implement your own logic here
}
boolean equals(Object obj) {
// implement your own logic here
}
}
精彩评论