java filter array by even numbers

https://‮l.www‬autturi.com
java filter array by even numbers

To filter an array of integers in Java by even numbers, you can use the filter() method of the Stream class. Here's an example of how to do it:

import java.util.Arrays;
import java.util.stream.IntStream;

public class Main {
  public static void main(String[] args) {
    int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // Filter the array to get only even numbers
    int[] evenNumbers = Arrays.stream(array)
      .filter(n -> n % 2 == 0)
      .toArray();

    // Print the even numbers
    System.out.println(Arrays.toString(evenNumbers));
  }
}

This code creates an array of integers and then uses the filter() method to remove all odd numbers. The toArray() method is used to collect the remaining elements into a new array.

Note that the filter() method takes a Predicate as an argument, which is a function that returns a boolean value. In this case, we use a lambda expression that checks if the number is even by checking if it's divisible by 2.

You can use a similar approach to filter an array of any type of data, as long as you use the appropriate Stream and the appropriate predicate to filter the elements.

Created Time:2017-11-03 15:57:14  Author:lautturi