Solved

What is the best way to sort array list?

Posted on 2007-12-05
11
974 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
  • 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
 

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

910 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now