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?
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.
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.
Ordering is great for this type of thing. Ordering.compound() allows you to chain the options in exactly the way that you have described.
精彩评论