I have a method that returns an int[]. The array is made by filtering out only the even values of the array passed into the method.
It works, but it's really ugly and inefficient. How can I condense this and do it more efficiently?
import java.util.Arrays;
public class SequentialSearcher {
public static void main(String[] args) {
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5};
System.out.println(Arrays.toString(even(arr)));
}
private static int[] even(int[] array) {
int[] newArr = new int[array.length];
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
newArr[i] = array[i];
}
}
int count = 0;
for (int num : newArr) {
if ((num % 2 == 0) && (num != 0)) {
count++;
}
}
int[] finalArr = new int[count];
int j = 0;
for (int k : newArr) {
if (k != 0) {
finalArr[j] = k;
j++;
}
}
return finalArr;
}
}