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:
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
We define a class called ApexUseCaseSeventeen, and inside it, a static method called findMinAndMax that accepts a list of integers.
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.
We initialize both minNumber and maxNumber to the first number in the list. We’ll compare all other numbers to these.
We loop through each number:
If the number is greater than or equal to the current max, update
maxNumberIf it’s smaller than the current min, update
minNumber
Simple logic. 💡
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
🎥 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.
Want to go further with this?
Learn it step by step in a course, or talk it through on a 1:1 call.
