Solved

What is the best way to sort array list?

Posted on 2007-12-05
11
979 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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jar file executable 12 60
servlet  URL Rewriting 1 42
reverse digits of a number using for loop 5 52
spring maven example issues 3 13
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

828 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