Ng Yong Loon
Ng Yong Loon

Reputation: 27

How to get maximum value in an ArrayList

I want to know how to compare the all array list element in the array list? Eg I want to compare element which is the largest number. Like comparing 1st element and 2nd element, 2nd element compares to the 3rd element. How to do it?

List <Product> productList= new ArrayList<>();

Can anyone give some example on how to compare with this variable?

productList.get(i).getPrice()

Thanks for help.

Upvotes: 2

Views: 3061

Answers (2)

Pushpendra
Pushpendra

Reputation: 2819

If you just want max value then use this:

public int getMax(ArrayList list){
    int max = Integer.MIN_VALUE;
    for(int i=0; i<list.size(); i++){
        if(list.get(i) > max){
            max = list.get(i);
        }
    }
    return max;
}

and more good way is comparator:

public class compareProduct implements Comparator<Product> {
    public int compare(Product a, Product b) {
        if (a.getPrice() > b.getPrice())
            return -1; // highest value first
        if (a.getPrice() == b.getPrice())
            return 0;
        return 1;
    }
}

and then just do this:

Product p = Collections.max(products, new compareProduct());

Upvotes: 7

Manohar
Manohar

Reputation: 23404

Compare some thing like this

for (int i = 0; i < productList.size(); i++) {

  for (int j = i+1; j < productList.size(); j++) {

    // compare productList.get(i)  and productList.get(j)

  }
}

Upvotes: 0

Related Questions