Solved

What is the best way to sort array list?

Posted on 2007-12-05
11
983 Views
Last Modified: 2010-04-21
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

0
Comment
Question by:vcaces
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 3
11 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 20415597
Use Arrays.sort with a Comparator built on the last name
0
 
LVL 92

Expert Comment

by:objects
ID: 20415618
use the following:

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

Expert Comment

by:CEHJ
ID: 20415628
Try
Collections.sort(books, new Comparator<Book>() {
	public int compare(Book b1, Book b2) {
		return b1.getLastName().compareTo(b2.getLastName());
	}
});

Open in new window

0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

Author Comment

by:vcaces
ID: 20415688
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

0
 
LVL 92

Expert Comment

by:objects
ID: 20415725
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===");
0
 
LVL 92

Expert Comment

by:objects
ID: 20415738
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());
   }
});
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20415750
>>if usibg java5+ then you can change it to:

(Already mentioned)
0
 

Author Comment

by:vcaces
ID: 20416603
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

0
 
LVL 92

Expert Comment

by:objects
ID: 20416642
whats the error?
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 20416694
sorry typo:

>                   Collections.sort(books,  new Comparator {

should be:

                  Collections.sort(books,  new Comparator() {

0
 

Author Closing Comment

by:vcaces
ID: 31412976
You are the best

Thx :)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question