Separate Even and Odd

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 71:-  Separate Even and Odd

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.

11. ArrayList

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?