Java sort ArrayList with custom fields by number and alphabetically

前端 未结 5 1661
醉梦人生
醉梦人生 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<Product>{
    
        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<Product>{
    
        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<Product>{
    
            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

    0 讨论(0)
  • 2020-12-19 05:47

    As far as I know , you dont have such methods , what you can do is ; extend a subclass of Collection and add methods to sort (search or techniques like bubble sort,and more)

    If you have facility for a database (more overhead) *you could put it in there and use order by *if you are using JPA , just dump your list into a entity class

    0 讨论(0)
  • 2020-12-19 05:55

    You need to implement the Comparable interface. The interface requires you to add a function called compareTo(Product other) within which you write the code that checks the custom fields you want the objects to be compared by.

    Alternatively you can do what @Prasad Kharkar suggested and write a Comaparator that essentially does the same thing.

    http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

    http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

    0 讨论(0)
  • 2020-12-19 05:57

    Have the Product class implement the Comparable interface.

    public class Product implements Serializable, Comparable<Product> {
    
            //Ommitted constructors, fields and accessors
    
        //This is an ascending sort order
        @Override
        public int compareTo(Product o) {
            int result = this.name.compareToIgnoreCase(o.name);
            if(result != 0){
                return result;
            }else{
                return new Double(this.price).compareTo(new Double(o.price));
            }   
        }
    }
    

    Then sorting is as easy as pass the List to Collections.sort():

    public static void main(String[] args) {
        Product p1 = new Product("p1", "shoes", 30.33, 20);
        Product p2 = new Product("p2", "shoes", 20.30, 20);
        Product p3 = new Product("p3", "shoes", 50.33, 20);
        Product p4 = new Product("p4", "socks", 10.50, 20);
        Product p5 = new Product("p5", "socks", 5.40, 20);
        Product p6 = new Product("p6", "socks", 2.34, 20);
    
        List<Product> products = Arrays.asList(p1,p2,p3,p4,p5,p6);
    
        System.out.println("Unsorted");
        for(Product product:products){
            System.out.println("Product: " + product.name + " Price: " + product.price);
        }
    
        Collections.sort(products);
    
        System.out.println("sorted");
        for(Product product:products){
            System.out.println("Product: " + product.name + " Price: " + product.price);
        }
    }
    

    Here is the full source for Product that implements Comparable with a sort example in the main method:

    import java.io.Serializable;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.List;
    
    public class Product implements Serializable, Comparable<Product> {
    
        private String id;
        private String name;
        private double price;
        private int quantity;
    
        public Product(String id, String name, double price, int quantity) {
            this.id = id;
            this.name = name;
            this.price = price;
            this.quantity = quantity;
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public double getPrice() {
            return price;
        }
    
        public void setPrice(double price) {
            this.price = price;
        }
    
        public int getQuantity() {
            return quantity;
        }
    
        public void setQuantity(int quantity) {
            this.quantity = quantity;
        }
    
        @Override
        public String toString() {
            return "Product{" + "id=" + id + ", name=" + name + ", price=" + price
                    + ", quantity=" + quantity + '}';
        }
    
        @Override
        public int compareTo(Product o) {
            int result = this.name.compareToIgnoreCase(o.name);
            if(result != 0){
                return result;
            }else{
                return new Double(this.price).compareTo(new Double(o.price));
            }
    
        }
    
        public static void main(String[] args) {
            Product p1 = new Product("p1", "shoes", 30.33, 20);
            Product p2 = new Product("p2", "shoes", 20.30, 20);
            Product p3 = new Product("p3", "shoes", 50.33, 20);
            Product p4 = new Product("p4", "socks", 10.50, 20);
            Product p5 = new Product("p5", "socks", 5.40, 20);
            Product p6 = new Product("p6", "socks", 2.34, 20);
    
            List<Product> products = Arrays.asList(p1,p2,p3,p4,p5,p6);
    
            System.out.println("Unsorted");
            for(Product product:products){
                System.out.println("Product: " + product.name + " Price: " + product.price);
            }
    
            Collections.sort(products);
    
            System.out.println("sorted");
            for(Product product:products){
                System.out.println("Product: " + product.name + " Price: " + product.price);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-19 06:12

    Use a Comparator<Product>, here implemented anonymously (suitable for java 7 and earlier):

    List<Product> list;
    Collections.sort(list, new Comparator<Product>() {
        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<Product> and implement it in the compareTo() method of Product.

    0 讨论(0)
提交回复
热议问题