Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sort ArrayList with custom fields by number and alphabetically

Tags:

java

sorting

public class Product implements Serializable{

    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 + '}';
    }

I want to sort ArrayList<Product> by price and name. I search Google for a long time but I cann't solve it. Whether it can have problem with Serializable

like image 810
haind Avatar asked Aug 19 '13 10:08

haind


People also ask

How do you sort an ArrayList in alphabetical order?

To sort the ArrayList, you need to simply call the Collections. sort() method passing the ArrayList object populated with country names. This method will sort the elements (country names) of the ArrayList using natural ordering (alphabetically in ascending order).

How do you sort collection of custom objects in Java?

In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.

Can you sort an ArrayList of objects Java?

An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.


2 Answers

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

like image 175
Prasad Kharkar Avatar answered Sep 22 '22 02:09

Prasad Kharkar


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);
        }
    }
}
like image 35
Kevin Bowersox Avatar answered Sep 24 '22 02:09

Kevin Bowersox