2

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!

1
  • It is not at all clear what you are looking for. Please elaborate. Explain problem with an example Jan 20, 2010 at 4:30

4 Answers 4

3

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).

2

[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)

1
  • 1
    You might be asking HOW to implement such a sorting mechanism, but that's generally not what you want to do in the business world ;). If this is homework, tag it as such and be more specific. Jan 20, 2010 at 4:32
1

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);
       }
    }
}
0
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
    }
}