简体   繁体   中英

Sorting ArrayList of objects with two properties

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM