-4

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.

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
  • 2
    possible duplicate of [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) – jor Feb 05 '15 at 11:08
  • use `Collections.sort()` with custom comparator – user902383 Feb 05 '15 at 11:09
  • and [how sort a ArrayList in java](http://stackoverflow.com/questions/18441846/how-sort-a-arraylist-in-java?lq=1).Please check SO before you ask a question – Droidekas Feb 05 '15 at 11:21
  • @Droidekas I tried that but it returns a null pointer and the numbers aren't null either. – Nehara Ranathunga Feb 05 '15 at 12:20
  • but the code you have accepted,is pretty much the same.So that should have worked too – Droidekas Feb 05 '15 at 12:31

2 Answers2

0

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
Yograj Shinde
  • 839
  • 12
  • 23
0

You can implement using Collections.sort(List<T> list, Comparator<? super T> c) as such

Collections.sort(productList, new Comparator<Product>() {
    @Override
    public int compare(Product p1, Product p2) {
        return p1.ProductRating - p2.ProductRating; // Ascending
    }
});
Vivek Singh
  • 3,641
  • 2
  • 22
  • 27