1

I am using JDK 1.7 for my project. I have come across Huddle. I have an ArrayList of objects which have two properties: price (decimal) and product name (String). I need to sort the ArrayList, first by price and then by product name. I've tried to use the Java comparator, but I can only sort by one property. Here is my code:

private static class PriceComparator implements Comparator<Product>{
 @Override
 public int compare(Product p1, Product p2) {
    return (p1.getPrice() > p2.getPrice() ) ? -1: (p1.getPrice() < p2.getPrice()) ?   
  1:0 ;
 }

}

This code only sort price, and not name.

Please i would apprecaite your help and example.

Thanks Ish

4
  • 4
    show us the comperator that you have written... Commented Mar 22, 2013 at 12:12
  • 1
    The Comparator should actually be enough. Make sure you first compare by price and then by product name. Commented Mar 22, 2013 at 12:13
  • 1
    write a comparator, that compares the first Value and if these values are equal it compares the second value. Commented Mar 22, 2013 at 12:13
  • one similar post stackoverflow.com/questions/369512/… Commented Mar 22, 2013 at 12:23

1 Answer 1

3

If you don't mind using an Apache Commons library, Commons Lang has a CompareToBuilder. You can use it to easily compare multiple fields. Primitives are handled automatically, but you can pass an optional custom Comparator for each field as well.

public class Product implements Comparable<Product> {
    private float price;
    private String name;
    ...
    @Override
    public int compareTo(Product other) {
        return new CompareToBuilder()
            .append(getPrice(), other.getPrice())
            .append(getName(), other.getName())
            .toComparison();
    }
    ...
}

Then just call Collections.sort() on the List.

List<Product> products = new ArrayList<Product>();
products.add(new Product("Adam's Product", 10.0))
products.add(new Product("Charlie's Product", 8.0))
products.add(new Product("Bob's Product", 8.0))
Collections.sort(products)

They will now be ordered as:

  1. Bob's Product
  2. Charlie's Product
  3. Adam's Product
Sign up to request clarification or add additional context in comments.

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.