User Story
Write a program that identifies even numbers in the following list using Apex in Salesforce.
List<Integer> myList = new List<Integer>{5, 1, 9, 11, 2, 4, 7, 14};
You have been given a List of integers called "myList". Your task is to create a new List called "evenList" that contains only the even numbers from "myList".
Expected Outcome
The even numbers in the list are: (2, 4, 14)
Solution 1
List<Integer> myList = new List<Integer>{5, 1, 9, 11, 2, 4, 7, 14};
List<Integer> evenList = new List<Integer>();
for(Integer num : myList){
if(Math.mod(num,2) == 0){
evenList.add(num);
}
}
System.debug('The even numbers in the list are: ' + evenList);
Solution 2
List<Integer> myList = new List<Integer>{5, 1, 9, 11, 2, 4, 7, 14};
List<Integer> evenList = new List<Integer>();
for(Integer i = 0; i < myList.size(); i++){
if(Math.mod(myList[i],2) == 0){
evenList.add(myList[i]);
}
}
System.debug('The even numbers in the list are: ' + evenList);
Video
Video does not exists.