Lee
Lee

Reputation: 37

Sorting List By Object Field

I'm getting a null pointer, not familiar with the compare methods and trying to figure out where I'm going wrong. The idea is I sort by the number of products sold and then get the top 5 products sold. It returns a NullPointer once I implement the compare methods.

public Result index() {
    // Get list of all categories in ascending order
    String name = "Best Sellers";
    List<Category> categoriesList = Category.findAll();
    List<Product> productsList;
    Long cat = new Long("11");
    productsList = bestSellers();

    return ok(index.render(env, categoriesList, productsList, cat, "", getCurrentUser(), name));
}


public List<Product> bestSellers(){
    List<Product> temp = Product.findAll("");
    Collections.sort(temp, new Comparator<Product>() {
         @Override
         public int compare(Product p1, Product p2) {
             if(p1.getCopiesSold()>p2.getCopiesSold()){
                return 1;
             } else if(p1.getCopiesSold()<p2.getCopiesSold()){
                 return -1;
             }
             return 0;
         }
    });

    List<Product> bestSellers = new ArrayList<>();
    for(int i=0; i<5; i++){
        bestSellers.add(temp.get(i));
    }
    return bestSellers;
}

My getter was returning null for some items that have yet to have a purchase so I just had to add a check for null and everything works fine.

public Integer getCopiesSold() {
    if(copiesSold==null){
        copiesSold = 0;
    }
    return copiesSold;
}

Upvotes: 0

Views: 54

Answers (1)

Information Aether
Information Aether

Reputation: 408

Check your method findAll(). It would appear that it is giving a list where some values have a value of null. When your compare method is called by the sorting algorithm used by Collections, p1.getCopiesSold or p2.getCopiesSold gives an error because p1 or p2 is null.

It is also possible that the method is findAll() is returning null and not a List, or that the method getCopiesSold returns null.

In java, something can have a value of null without throwing an exception, it only throws an exception when you try to call a method or preform an operation with it. Because of this, the null variable could be any of the variables being used by the line throwing the error.

Upvotes: 1

Related Questions