Salesforce List (Array) :How to Find the MAX value in a list

4:45 PM

Update: There's a simple way as pointed out by Scott Hemmeter in his comment below. Just use the sort() method and the first element in the list is the MAX or MIN based upon your sort (DESC or ASC). Thanks, Scott


This is just a way that i followed, not sure if LIST's have a pre-defined function to find out the maximum... If you do find a easier way, share it in the comments box below.

Here, "samplevalues" is a LIST of Decimal's

List<Decimal> samplevalues = new List<Decimal>();
samplevalues.add(55.0);
samplevalues.add(75.5);
samplevalues.add(99.3);
Decimal maxvalue = samplevalues[0];
        For (integer i =0;i<samplevalues.size();i++)
        {
            
            if( samplevalues[i] > maxvalue)
                maxvalue = samplevalues[i];             
        }    
system.debug('the max value is'+maxvalue);  

2 comments

  1. Lists do have a sort() method. Could that eliminate the loop?

    ReplyDelete
  2. Oh yeah!!, the first element in the list after sorting is the max/min.. Thanks for bringing that up

    ReplyDelete

AD