package com.candidjava; import java.util.ArrayList; import java.util.Collections; class Author implements Comparable<Author> { String authorname; String bookname; int bookprice; // constructor for author Author(String authorname, String bookname, int bookprice) { this.authorname = authorname; this.bookname = bookname; this.bookprice = bookprice; } // Printing Author in the main public String toString() { return this.authorname + " " + this.bookname + " " + this.bookprice; } public String getAuthorname() { return authorname; } public void setAuthorname(String authorname) { this.authorname = authorname; } @Override public int compareTo(Author o) { return this.getAuthorname().compareTo(o.getAuthorname()); } } public class Arraylistsortcomparable { public static void main(String[] args) { ArrayList<Author> al = new ArrayList<Author>(); al.add(new Author("Shakespeare", "The Tragedy of Macbeth", 300)); al.add(new Author("Shakespeare", "The Winters Tale", 350)); al.add(new Author("Vairamuthu", "Moondram ulaga por", 500)); al.add(new Author("Dr.A.P.J", "Agni siragugal", 200)); al.add(new Author("James Gosling", "JAVA Programming Language", 400)); System.out.println("Unsorted Arraylist"); for (int i = 0; i < al.size(); i++) { System.out.println(al.get(i)); } // Ascending Order System.out.println("--------------------------------------------"); System.out.println("Sorted Array list"); System.out.println("--------------------------------------------"); Collections.sort(al); for (int i = 0; i < al.size(); i++) { System.out.println(al.get(i)); } } }
OUTPUT
Unsorted Arraylist Shakespeare The Tragedy of Macbeth 300 Shakespeare The Winters Tale 350 Vairamuthu Moondram ulaga por 500 Dr.A.P.J Agni siragugal 200 James Gosling JAVA Programming Language 400 -------------------------------------------- Sorted Array list -------------------------------------------- Dr.A.P.J Agni siragugal 200 James Gosling JAVA Programming Language 400 Shakespeare The Tragedy of Macbeth 300 Shakespeare The Winters Tale 350 Vairamuthu Moondram ulaga por 500