Nehara Ranathunga Nehara Ranathunga - 1 year ago 68
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.


String ProductID;
int ProductRating;

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

Answer Source

Use following solution

public class ProductRatingSort implements Comparator<Product> {

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

       return 1;
    return -1;

and then call this from where you want to sort arraylist

Collections.sort(arrProduct, new ProductRatingSort());   // your array list
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download