Java sort ArrayList with custom fields by number and alphabetically

前端 未结 5 1674
醉梦人生
醉梦人生 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 05:47

    You need to implement Comparable or Comparator interface for your purpose. sorting user defined objects with Comparator and sorting user defined objects with comparable

    You can learn the difference between these two by reading these tutorials

    Consider you want your products to be sorted using its price then make your Product implement Comparable as follows

    public class Product implements Comparable{
    
        public int compareTo(Product other){
           // your logic here
        }
    
    }
    

    But hold on... now that we have already implemented Comparable interface to sort the objects using its price, how can we sort them using another sort sequence? We only have one compareTo() method and we can't write separate sort sequence in the same class. Here comes the role of Comparator. With Comparator, you can define multiple sort sequences.

    Suppose we want to sort using its price, then:

    public class PriceSorter implements Comparator{
    
        public int compare(Product one, Product another){
            int returnVal = 0;
    
        if(one.getPrice() < another.getPrice()){
            returnVal =  -1;
        }else if(one.getPrice() > another.getPrice()){
            returnVal =  1;
        }else if(one.getPrice() == another.getPrice()){
            returnVal =  0;
        }
        return returnVal;
        }
    }
    

    and you want another sort sequence, now for its name, then:

    public class NameSorter implements Comparator{
    
            public int compare(Product one, Product another){
                return one.getName().compareTo(another.getName());
            }
    }
    

    Now, when you want to sort using price, then

    Collections.sort(yourList,new PriceSorter());
    

    If you want to sort using name, then

    Collections.sort(yourList, new NameSorter());
    

    The second argument takes the Comparator instance which makes the sort method know what logic to follow while sorting objects

提交回复
热议问题