Want to figure out the smallest and largest numbers in a list using Apex? You’ve come to the right place!
In this blog post, we’ll walk through a method that takes a list of integers and returns the maximum and minimum numbers from it. This is a super common task whether you’re working with scores, prices, or even temperature data. 📊
This simple logic is beginner-friendly and helps you get more comfortable with loops, comparisons, and list handling in Apex.
🧠 What Are We Trying to Do?
Let’s say we pass this list to our method:
[7, 5, 65, 799, 8]
We want to:
Find the largest number (799)
Find the smallest number (5)
Return both in a new list:
[799, 5]
That’s exactly what this method does!
🔍 Code Explanation
public with sharing class ApexUseCaseSeventeen {
public static List<Integer> findMinAndMax(List<Integer> listOfNumbers){
We define a class called ApexUseCaseSeventeen
, and inside it, a static method called findMinAndMax
that accepts a list of integers.
List<Integer> minAndMaxList = new List<Integer>();
if(listOfNumbers.size() > 0){
We create an empty list to hold the min and max values. Then we check if the input list is not empty to avoid errors.
Integer minNumber = listOfNumbers[0];
Integer maxNumber = listOfNumbers[0];
We initialize both minNumber
and maxNumber
to the first number in the list. We’ll compare all other numbers to these.
for(Integer eachNum : listOfNumbers){
if(eachNum >= maxNumber){
maxNumber = eachNum;
}
if(eachNum < minNumber){
minNumber = eachNum;
}
}
We loop through each number:
If the number is greater than or equal to the current max, update
maxNumber
If it’s smaller than the current min, update
minNumber
Simple logic. 💡
minAndMaxList.add(maxNumber);
minAndMaxList.add(minNumber);
}
return minAndMaxList;
}
}
After the loop finishes, we add both maxNumber
and minNumber
to our result list and return it.
✅ Why This Is Useful
This kind of logic is incredibly helpful when you need to:
Summarize data (like highest/lowest scores)
Compare prices or metrics
Build dashboards or reports
It’s also a great exercise in working with:
Loops
If-conditions
Lists and return values
You can easily expand it to:
Work with decimals
Return a map with keys like
"min"
and"max"
Include null checks or validations
🧾 Final Code Snippet
public with sharing class ApexUseCaseSeventeen {
public static List<Integer> findMinAndMax(List<Integer> listOfNumbers){
List<Integer> minAndMaxList = new List<Integer>();
if(listOfNumbers.size() > 0){
Integer minNumber = listOfNumbers[0];
Integer maxNumber = listOfNumbers[0];
for(Integer eachNum : listOfNumbers){
if(eachNum >= maxNumber){
maxNumber = eachNum;
}
if(eachNum < minNumber){
minNumber = eachNum;
}
}
minAndMaxList.add(maxNumber);
minAndMaxList.add(minNumber);
}
return minAndMaxList;
}
}
🎥 Watch It in Action!
Want to see how it works step-by-step? Check out my quick demo where I run this method using sample data in the Developer Console.