🔹 Introduction
Separating even and odd numbers is a common Java interview question.
It helps test your understanding of Java Streams, filtering, and partitioning.
👉 In this article, we will solve this using:
- Traditional approach
- Java Streams (modern approach)
🔹 Problem Statement
Given a list of integers, separate even and odd numbers.
Example:
Input: [1, 2, 3, 4, 5, 6]
Output: Even: [2, 4, 6], Odd: [1, 3, 5]
🔹 Approach 1: Using Loop (Basic)
💡 Explanation
- Traverse list
- Check number % 2
- Store in separate lists
👨💻 Java Code
import java.util.*;
public class EvenOdd {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
List<Integer> even = new ArrayList<>();
List<Integer> odd = new ArrayList<>();
for (int num : list) {
if (num % 2 == 0) {
even.add(num);
} else {
odd.add(num);
}
}
System.out.println("Even: " + even);
System.out.println("Odd: " + odd);
}
}
🔹 Approach 2: Using Java Streams (Recommended)
💡 Explanation
-
Use
partitioningBy() - It splits data into two groups (true/false)
👉 true → even
👉 false → odd
👨💻 Java Code (Streams)
import java.util.*;
import java.util.stream.*;
public class EvenOdd {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
Map<Boolean, List<Integer>> result =
list.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println("Even: " + result.get(true));
System.out.println("Odd: " + result.get(false));
}
}
🔹 Output
Even: [2, 4, 6]
Odd: [1, 3, 5]
🔹 Time Complexity
- O(n)
🔹 Key Takeaways
✔ partitioningBy() is very important
✔ Streams make code concise
✔ Frequently asked in interviews
🔹 Conclusion
This is a must-know Java Streams problem.
Understanding partitioningBy() helps in solving many real-world problems.
🔗 Also Read
👉 First Non-Repeating Character in Java
👉 Check Palindrome String in Java
👉 Reverse a String
👉 Count Character Frequency in Java
Comments
Post a Comment