Problem Statement: Write a Java program to create a method that partitions an ArrayList of integers into two separate lists, one containing even numbers and the other containing odd numbers.
Here’s a Java program that demonstrates how to create a method to partition an ArrayList
of integers into two separate lists, one containing even numbers and the other containing odd numbers.
package com.javacodepoint.collection;
import java.util.ArrayList;
import java.util.List;
public class PartitionArrayList {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(25);
numbers.add(6);
numbers.add(15);
numbers.add(30);
numbers.add(7);
System.out.println("Original List: " + numbers);
// Partition the list into even and odd lists
List<Integer> evenList = new ArrayList<>();
List<Integer> oddList = new ArrayList<>();
partitionArrayList(numbers, evenList, oddList);
System.out.println("Even Numbers List: " + evenList);
System.out.println("Odd Numbers List: " + oddList);
}
// Method to partition an ArrayList into even and odd lists
public static void partitionArrayList(List<Integer> originalList, List<Integer> evenList, List<Integer> oddList) {
for (Integer number : originalList) {
if (number % 2 == 0) {
evenList.add(number); // Even number, add to even list
} else {
oddList.add(number); // Odd number, add to odd list
}
}
}
}
OUTPUT:
Original List: [10, 25, 6, 15, 30, 7]
Even Numbers List: [10, 6, 30]
Odd Numbers List: [25, 15, 7]
Explanation:
- Creating the List: We create an
ArrayList
namednumbers
and populate it with some integers. - Printing the Original List: We print the contents of the
numbers
list usingSystem.out.println()
. - Partitioning the List: We create two new
ArrayLists
,evenList
andoddList
, to store even and odd numbers, respectively. We then call thepartitionArrayList()
method to perform the partitioning. partitionArrayList()
Method: This method takes three parameters: the original list (originalList
), the list for even numbers (evenList
), and the list for odd numbers (oddList
).- Iterating Through the Original List: We use a
for-each
loop to iterate through each number in theoriginalList
. - Partitioning Even and Odd Numbers: Inside the loop, we check if the number is even or odd using the modulo operator (
%
). If the remainder when dividing the number by 2 is 0, it’s even and gets added to theevenList
. Otherwise, it’s odd and gets added to theoddList
. - Printing the Result Lists: Finally, we print the contents of both the
evenList
andoddList
to display the partitioned numbers.
By using a method to iterate through the original list and separate even and odd numbers into two different lists, the program effectively partitions the ArrayList
into two separate lists while preserving the order of elements.
See also: Find common elements in two ArrayLists in Java.