0

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?

1

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

A single comparator is enough. It's only important to compare the 3 conditions in the right order.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.