public class Product implements Serializable{
private String id;
private String name;
private double price ;
private int quantity;
public Produ
Use a Comparator
, here implemented anonymously (suitable for java 7 and earlier):
List list;
Collections.sort(list, new Comparator() {
public int compare(Product a, Product b) {
if (a.getPrice() == b.getPrice())
return a.getName().compareTo(b.getName());
return a.getPrice() > b.getPrice() ? 1 : a.getPrice() < b.getPrice() ? -1 : 0
}
});
Java 8 has a much cleaner way of achieving the above:
Collections.sort(list, Comparator.comparing(Product::getPrice).thenComparing(Product::getName));
If this defines the "natural order" of your products, consider making Product
implement Comparable
and implement it in the compareTo()
method of Product
.