views:

73

answers:

3

My Book app gathers a collection of Book objects using lookups against different Merchant objects:

List<Book> books = new ArrayList<Book>();
for (Merchant merchant : merchants)
{
    books.addAll(getBooksForMerchant(merchantName);
}

It has to sort the List on the basis of a dropdown box:

<select class="sortByDropdown" name="sort">
<option value="lowPrice">Price: Low to High</option>
<option value="highPrice">Price: High to Low</option>
<option value="reviewRank">Avg. Customer Review</option>
</select>

Given that a Book has a price property and a reviewRank property, how would I sort the ArrayList of Books in Java before displaying it to the user in the order they requested?

+4  A: 

Do it in the same way as you would sort any List. Implement a Comparator and call Collections.sort(list, comparator).

Having 3 different ways of sorting means you might need to create 3 implementations, or a single one that you can control to sort 3 ways.

Qwerky
A single comparator is enough. It's only important to compare the 3 conditions in the right order.
Johannes Wachter
A: 

Almost the exact same question was asked yesterday:

Short answer, depending on how flexible your solution needs to be, you could write one Comparator, or write several and compose them together for complex sorting requirements.

romacafe
A: 

Ordering is great for this type of thing. Ordering.compound() allows you to chain the options in exactly the way that you have described.

gk5885