Link to home
Start Free TrialLog in
Avatar of vcaces
vcaces

asked on

What is the best way to sort array list?

How can I sort this ArrayList by the AuthorLastName? Is there a lot of swapping?
/**********************************************************
*Author: Joshua.vangulden
*File Name: BookDriver.java
*CS219 HW#4
*
*This program is to help add new books, Author name and
*the price.
**********************************************************/
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
 
public class BookDriver {
  public static void main(String[] args) {
 
/*************raw data for input**************/
 
		String [] tittle = {"Band of Brothers", "Beloved", "Catch-22", "East of Eden",
							"Harry Potter and the Goblet of fire", "Of Mice and Men",
							"The Catcher in the Rye", "The Grapes Of Wrath",
							"To Kill a Mockingbird"}; //name of book
		String [] lname = {"Ambrose", "Morrison", "Heller", "Steinbeck", "Rowling",
						"Steinbeck", "Salinger", "Steinbeck", "Lee"} ; // Author Last Name
		String [] fname = {"Stephen E.", "Toni", "Joseph", "John", "J.K.", "John", "J.D.",
						"John", "Harper"} ; // Author first Name
		int [] qty = {10, 23, 12, 45, 2, 13, 11, 17, 8} ; // numbers of books in store
		double [] price = {9.60, 12.95, 12.00, 12.95, 18.16, 6.95, 5.99, 13.00, 18.00}; // price of each book
		//Book books;
 
/******* Sort the book by Author last name ********/
 
        ArrayList <Book> books = new ArrayList <Book>();//Array list of Book lists
 
		//Make a bookslist
 
        	books.add(new Book("Band of Brothers", "Ambrose", "Stephen E.", 10, 9.60));
        	books.add(new Book("Beloved", "Morrison","Toni", 23, 12.95));
        	books.add(new Book("Catch-22","Heller","Joseph",12, 12.00));
        	books.add(new Book("East of Eden","Steinbeck","John",45, 12.95));
        	books.add(new Book("Harry Potter and the Goblet of Fire","Rowling","J.K.",2, 18.16));
        	books.add(new Book("Of Mice and Men","Steinbeck","John",13,6.95));
        	books.add(new Book("The Catcher in the Rye","Salinger","J.D.",11, 5.99));
        	books.add(new Book("The Grapes of Wrath","Steinbeck", "John", 17, 13.00));
        	books.add(new Book("To Kill a Mockingbird","Lee","Harper",8, 18.00));
 
        	//System.out.println("my Book List"+ books.toString());
 
        	System.out.println("===my Book List===");
			for (int i=0; i<books.size(); i++){
			    Book book=books.get(i);
			    System.out.print((i+1)+")");
			    System.out.println(book.getTitle()+"  "+book.getAuthorFirstName()+" "+
			    					book.getAuthorLastName()+"  "+book.getPrice()+"  "+book.getQuantity());
 
			    System.out.println();
			}// end for i loop
			System.out.println("===my Book List Ended===");
 
 
	  	// sort by the Auther Last name.;
 
 
 
 
 
 
/******** print to screen ************/
 
		System.out.println ("                           Book Report. Sorted by author");
		System.out.println (" ------------------------------------------------------------------------------");
		System.out.println ("	Title				Last Name   First Name    Qty     Price");
		System.out.println (" ------------------------------------------------------------------------------");
 
		for(int i=0; i<qty.length; i++){
			System.out.printf("%-40s%-12s%-12s%5d%10.2f\n", tittle[i], lname[i], fname[i], qty[i], price[i]);
 
		}// end i for loop
 
		System.out.println();
 
 
  } // end main
 
} // end class SalesManagerDriver

Open in new window

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Use Arrays.sort with a Comparator built on the last name
use the following:

Collections.sort(books,  new Comparator {
   public int compare(Object a, Object b) {
      return ((Book)a).getAuthorLastName().compareTo(((Book)b).getAuthorLastName());
   }
});
Try
Collections.sort(books, new Comparator<Book>() {
	public int compare(Book b1, Book b2) {
		return b1.getLastName().compareTo(b2.getLastName());
	}
});

Open in new window

Avatar of vcaces
vcaces

ASKER

this is where I put the Comparator I doing think it is in the right place.
/**********************************************************
*Author: Joshua.vangulden
*File Name: BookDriver.java
*CS219 HW#4
*
*This program is to help add new books, Author name and
*the price.
**********************************************************/
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
 
public class BookDriver {
  public static void main(String[] args) {
 
/*************raw data for input**************/
 
		String [] tittle = {"Band of Brothers", "Beloved", "Catch-22", "East of Eden",
							"Harry Potter and the Goblet of fire", "Of Mice and Men",
							"The Catcher in the Rye", "The Grapes Of Wrath",
							"To Kill a Mockingbird"}; //name of book
		String [] lname = {"Ambrose", "Morrison", "Heller", "Steinbeck", "Rowling",
						"Steinbeck", "Salinger", "Steinbeck", "Lee"} ; // Author Last Name
		String [] fname = {"Stephen E.", "Toni", "Joseph", "John", "J.K.", "John", "J.D.",
						"John", "Harper"} ; // Author first Name
		int [] qty = {10, 23, 12, 45, 2, 13, 11, 17, 8} ; // numbers of books in store
		double [] price = {9.60, 12.95, 12.00, 12.95, 18.16, 6.95, 5.99, 13.00, 18.00}; // price of each book
		//Book books;
 
/******* Sort the book by Author last name ********/
 
        ArrayList <Book> books = new ArrayList <Book>();//Array list of Book lists
 
		//Make a bookslist
 
        	books.add(new Book("Band of Brothers", "Ambrose", "Stephen E.", 10, 9.60));
        	books.add(new Book("Beloved", "Morrison","Toni", 23, 12.95));
        	books.add(new Book("Catch-22","Heller","Joseph",12, 12.00));
        	books.add(new Book("East of Eden","Steinbeck","John",45, 12.95));
        	books.add(new Book("Harry Potter and the Goblet of Fire","Rowling","J.K.",2, 18.16));
        	books.add(new Book("Of Mice and Men","Steinbeck","John",13,6.95));
        	books.add(new Book("The Catcher in the Rye","Salinger","J.D.",11, 5.99));
        	books.add(new Book("The Grapes of Wrath","Steinbeck", "John", 17, 13.00));
        	books.add(new Book("To Kill a Mockingbird","Lee","Harper",8, 18.00));
 
        	//System.out.println("my Book List"+ books.toString());
 
			Collections.sort(books, new Comparator<Book>() {
			   public int compare(Book b1, Book b2) {
			            return b1.getlastName().compareTo(b2.getlastName());
			        }
			});
 
        	System.out.println("===my Book List===");
			for (int i=0; i<books.size(); i++){
			    Book book=books.get(i);
			    System.out.print((i+1)+")");
			    System.out.println(book.getTitle()+"  "+book.getAuthorFirstName()+" "+
			    					book.getAuthorLastName()+"  "+book.getPrice()+"  "+book.getQuantity());
 
			    System.out.println();
			}// end for i loop
			System.out.println("===my Book List Ended===");
 
 
 
	  	// sort by the Auther Last name.;
 
 
 
 
 
 
/******** print to screen ************/
 
		System.out.println ("                           Book Report. Sorted by author");
		System.out.println (" ------------------------------------------------------------------------------");
		System.out.println ("	Title				Last Name   First Name    Qty     Price");
		System.out.println (" ------------------------------------------------------------------------------");
 
		for(int i=0; i<qty.length; i++){
			System.out.printf("%-40s%-12s%-12s%5d%10.2f\n", tittle[i], lname[i], fname[i], qty[i], price[i]);
 
		}// end i for loop
 
		System.out.println();
 
 
  } // end main
 
} // end class SalesManagerDriver

Open in new window

you haven't copied the code i posted correctly,
should be:

...
                System.out.println("===my Book List===");
                        for (int i=0; i<books.size(); i++){
                            Book book=books.get(i);
                            System.out.print((i+1)+")");
                            System.out.println(book.getTitle()+"  "+book.getAuthorFirstName()+" "+
                                                                book.getAuthorLastName()+"  "+book.getPrice()+"  "+book.getQuantity());
 
                            System.out.println();
                        }// end for i loop
                        System.out.println("===my Book List Ended===");
 
 
 
                // sort by the Auther Last name.;

Collections.sort(books,  new Comparator {
   public int compare(Object a, Object b) {
      return ((Book)a).getAuthorLastName().compareTo(((Book)b).getAuthorLastName());
   }
});


                System.out.println("===my sorted Book List===");
                        for (int i=0; i<books.size(); i++){
                            Book book=books.get(i);
                            System.out.print((i+1)+")");
                            System.out.println(book.getTitle()+"  "+book.getAuthorFirstName()+" "+
                                                                book.getAuthorLastName()+"  "+book.getPrice()+"  "+book.getQuantity());
 
                            System.out.println();
                        }// end for i loop
                        System.out.println("===my Book List Ended===");
if usibg java5+ then you can change it to:

Collections.sort(books,  new Comparator<Book> {
   public int compare(Book a, Book b) {
      return a.getAuthorLastName().compareTo(b.getAuthorLastName());
   }
});
>>if usibg java5+ then you can change it to:

(Already mentioned)
Avatar of vcaces

ASKER

Object I copy the code and it is giving me an Compile error.
/**********************************************************
*Author: Joshua.vangulden
*File Name: BookDriver.java
*CS219 HW#4
*
*This program is to help add new books, Author name and
*the price.
**********************************************************/
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
 
public class BookDriver {
  public static void main(String[] args) {
 
/*************raw data for input**************/
 
		String [] tittle = {"Band of Brothers", "Beloved", "Catch-22", "East of Eden",
							"Harry Potter and the Goblet of fire", "Of Mice and Men",
							"The Catcher in the Rye", "The Grapes Of Wrath",
							"To Kill a Mockingbird"}; //name of book
		String [] lname = {"Ambrose", "Morrison", "Heller", "Steinbeck", "Rowling",
						"Steinbeck", "Salinger", "Steinbeck", "Lee"} ; // Author Last Name
		String [] fname = {"Stephen E.", "Toni", "Joseph", "John", "J.K.", "John", "J.D.",
						"John", "Harper"} ; // Author first Name
		int [] qty = {10, 23, 12, 45, 2, 13, 11, 17, 8} ; // numbers of books in store
		double [] price = {9.60, 12.95, 12.00, 12.95, 18.16, 6.95, 5.99, 13.00, 18.00}; // price of each book
		//Book books;
 
/******* Sort the book by Author last name ********/
 
        ArrayList <Book> books = new ArrayList <Book>();//Array list of Book lists
 
		//Make a bookslist
 
        	books.add(new Book("Band of Brothers", "Ambrose", "Stephen E.", 10, 9.60));
        	books.add(new Book("Beloved", "Morrison","Toni", 23, 12.95));
        	books.add(new Book("Catch-22","Heller","Joseph",12, 12.00));
        	books.add(new Book("East of Eden","Steinbeck","John",45, 12.95));
        	books.add(new Book("Harry Potter and the Goblet of Fire","Rowling","J.K.",2, 18.16));
        	books.add(new Book("Of Mice and Men","Steinbeck","John",13,6.95));
        	books.add(new Book("The Catcher in the Rye","Salinger","J.D.",11, 5.99));
        	books.add(new Book("The Grapes of Wrath","Steinbeck", "John", 17, 13.00));
        	books.add(new Book("To Kill a Mockingbird","Lee","Harper",8, 18.00));
 
        	//System.out.println("my Book List"+ books.toString());
 
			System.out.println("===my Book List===");
			for (int i=0; i<books.size(); i++){
			     Book book=books.get(i);
			     System.out.print((i+1)+")");
			     System.out.println(book.getTitle()+"  "+book.getAuthorFirstName()+" "+
			                       book.getAuthorLastName()+"  "+book.getPrice()+"  "+book.getQuantity());
 
			     System.out.println();
			}// end for i loop
			System.out.println("===my Book List Ended===");
 
			// sort by the Auther Last name.;
 
			Collections.sort(books,  new Comparator {
			   public int compare(Object a, Object b) {
			      return ((Book)a).getAuthorLastName().compareTo(((Book)b).getAuthorLastName());
			   }
			});
 
 
			 System.out.println("===my sorted Book List===");
			 for (int i=0; i<books.size(); i++){
			      Book book=books.get(i);
			      System.out.print((i+1)+")");
			      System.out.println(book.getTitle()+"  "+book.getAuthorFirstName()+" "+
			                        book.getAuthorLastName()+"  "+book.getPrice()+"  "+book.getQuantity());
 
			       System.out.println();
			  }// end for i loop
              System.out.println("===my Book List Ended===");
 
/******** print to screen ************/
 
		System.out.println ("                           Book Report. Sorted by author");
		System.out.println (" ------------------------------------------------------------------------------");
		System.out.println ("	Title				Last Name   First Name    Qty     Price");
		System.out.println (" ------------------------------------------------------------------------------");
 
		for(int i=0; i<qty.length; i++){
			System.out.printf("%-40s%-12s%-12s%5d%10.2f\n", tittle[i], lname[i], fname[i], qty[i], price[i]);
 
		}// end i for loop
 
		System.out.println();
 
 
  } // end main
 
} // end class SalesManagerDriver

Open in new window

whats the error?
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of vcaces

ASKER

You are the best

Thx :)