Filter Even Numbers (Loop vs Streams)
Problem
Print the even numbers of the array in the same order. Print nothing (an empty line) if there are none.
Constraints
- 1 <= n <= 10^5
Examples
Input
6 1 2 3 4 5 6
Output
2 4 6
Solutions
Without streams you need a loop and a temporary list. The loop is clear and works in every Java version.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The even numbers.
* Approach: Filter the array.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a) {
// Step 1: Before Java 16 we used a loop and a list to keep the even numbers.
java.util.List<Integer> evens = new java.util.ArrayList<>();
for (int value : a) {
if (value % 2 == 0) {
evens.add(value);
}
}
// Step 2: Copy the list into an int array.
int[] result = new int[evens.size()];
for (int i = 0; i < result.length; i++) {
result[i] = evens.get(i);
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- Which numbers have value % 2 == 0?