Edit: Per your reply, the way to do this by taking user input has been written in a separate method at the bottom :)
You can implement a Comparator. You can create ones for each of the fields that you want like this:
public class Book {
int id;
String title;
String author;
Double price;
public Book(int id, String title, String author, Double price) {
super();
this.id = id;
this.title = title;
this.author = author;
this.price = price;
}
// getters and setters here
}
class CompareByID implements Comparator<Book> {
public int compare(Book one, Book two) {
return one.id - two.id;
}
}
class CompareByTitle implements Comparator<Book> {
public int compare(Book one, Book two) {
return one.title.compareTo(two.title);
}
}
class CompareByAuthor implements Comparator<Book> {
public int compare(Book one, Book two) {
return one.author.compareTo(two.author);
}
}
class CompareByPrice implements Comparator<Book> {
public int compare(Book one, Book two) {
if(one.price < two.price)
return -1;
if(two.price < one.price)
return 1;
return 0;
}
}
And then you can use it like this:
Book bookOne = new Book(1, "Harry Potter and the Comparator Operator", "Java Rowling", 19.99);
Book bookTwo = new Book(2, "Answering StackOverflow instead of doing your job at work", "Djharten", 0.01);
ArrayList<Book> bookList = new ArrayList<>();
bookList.add(bookOne);
bookList.add(bookTwo);
Collections.sort(bookList, new CompareByID());
for(Book b : bookList) {
System.out.println(b.getId());
}
Collections.sort(bookList, new CompareByAuthor());
for(Book b : bookList) {
System.out.println(b.getAuthor());
}
Collections.sort(bookList, new CompareByTitle());
for(Book b : bookList) {
System.out.println(b.getTitle());
}
Collections.sort(bookList, new CompareByPrice());
for(Book b : bookList) {
System.out.println(b.getPrice());
}
Output:
1
2
Djharten
Java Rowling
Answering StackOverflow instead of doing your job at work
Harry Potter and the Comparator Operator
0.01
19.99
I hope that helps!
Edit: New method to take user input of 4 Book Objects per your question(this assumes they input the correct input, I'll let you handle the exceptions possibilities):
public static List<Book> createBookList() {
List<Book> bookList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the book information for 4 books in this format: ID Title Author Price");
for(int i = 0; i < 4; i++) {
int id = sc.nextInt();
String title = sc.next();
String author = sc.next();
double price = sc.nextDouble();
Book book = new Book(id, title, author, price);
bookList.add(book);
sc.nextLine();
}
return bookList;
}