If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To separate even and odd numbers from an ArrayList
in Java, you can create two separate ArrayList
instances, one for even numbers and another for odd numbers. Then, iterate through the original list, check if each element is even or odd, and add it to the respective new lists accordingly. Here's a step-by-step implementation:
javaCopy code
import java.util.ArrayList;
public class SeparateEvenAndOdd {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(12);
numbers.add(7);
numbers.add(8);
numbers.add(5);
numbers.add(18);
numbers.add(6);
numbers.add(10);
// Separate even and odd numbers
ArrayList<Integer> evenNumbers = new ArrayList<>();
ArrayList<Integer> oddNumbers = new ArrayList<>();
for (Integer num : numbers) {
if (num % 2 == 0) {
evenNumbers.add(num);
} else {
oddNumbers.add(num);
}
}
// Print the separate lists
System.out.println("Even numbers: " + evenNumbers);
System.out.println("Odd numbers: " + oddNumbers);
}
}
Output:
lessCopy code
Even numbers: [12, 8, 18, 6, 10]
Odd numbers: [7, 5]
In this example, we create an ArrayList
called numbers
containing various integers. Then, we create two new ArrayList
instances: evenNumbers
to store even numbers and oddNumbers
to store odd numbers.
We iterate through the numbers
list, and for each element, we use the modulo operator %
to check if it is even or odd. If it's even (i.e., the remainder of num % 2
is 0), we add it to the evenNumbers
list. Otherwise, we add it to the oddNumbers
list.
Finally, we print the contents of both lists to see the separated even and odd numbers.
Comments: 0