Nehara Ranathunga Nehara Ranathunga - 1 year ago 44
Java Question

Java: Sorting (Items in ArrayList by their Properties

I have objects of type "Product" and an ArrayList of type 'Product' that contains multiple Product Objects.

Product

String ProductID;
int ProductRating;


I would like to traverse the
ArrayList
and sort these Products by their ProductRating; Highest to Lowest, so that the first item in the
ArrayList
contains the Highest rating and then decreasing thereafter.

Y.S Y.S
Answer Source

Use following solution

public class ProductRatingSort implements Comparator<Product> {

@Override
public int compare(Product arg0, Product arg1) {
    // TODO Auto-generated method stub
    int f = arg0.getProductRating();
    int s = arg1.getProductRating();

      if(f>s)
       return 1;
    return -1;
}
}

and then call this from where you want to sort arraylist

Collections.sort(arrProduct, new ProductRatingSort());   // your array list