2

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.

4
  • do you need to Sort the list? Commented Jan 4, 2017 at 10:17
  • dont need, I want to get the largest number in the arraylist Commented Jan 4, 2017 at 10:18
  • yeah, sort your array and get first or last element Commented Jan 4, 2017 at 10:18
  • then check every value using for loop, and store the largest Commented Jan 4, 2017 at 10:18

2 Answers 2

7

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());

Sign up to request clarification or add additional context in comments.

1 Comment

Shortest version Integer.compare(a.getPrice(), b.getPrice())
0

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)

  }
}

1 Comment

why to use inner loop? You can compare productList.get(i) and max

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.