Java sort ArrayList with custom fields by number and alphabetically

前端 未结 5 1662
醉梦人生
醉梦人生 2020-12-19 05:24
public class Product implements Serializable{

    private String id;
    private String name;
    private double price ;
    private int quantity;

    public Produ         


        
5条回答
  •  北海茫月
    2020-12-19 06:12

    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.

提交回复
热议问题