Solved

What is the best way to sort array list?

Posted on 2007-12-05
11
971 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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

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…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

757 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

21 Experts available now in Live!

Get 1:1 Help Now