Java 8 Program to Print Even Numbers from a List

1. Introduction

In modern Java programming, working with collections and streams has been greatly simplified with the introduction of the Stream API in Java 8. This blog post demonstrates how to use Java 8 features to filter and print even numbers from a list. This example is an excellent showcase of the power and simplicity of using streams for data processing.

2. Program Steps

1. Create a list of integers.

2. Use the Stream API to filter even numbers from the list.

3. Print the filtered even numbers.

3. Code Program

import java.util.Arrays;
import java.util.List;

public class PrintEvenNumbers {
    public static void main(String[] args) {
        // Creating a list of integers
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Using Stream API to filter and print even numbers
        System.out.println("Even numbers:");
        numbers.stream() // Converting the list to a stream
               .filter(n -> n % 2 == 0) // Filtering even numbers
               .forEach(System.out::println); // Printing each even number
    }
}

Output:

Even numbers:
2
4
6
8
10

Explanation:

1. The program starts by importing the necessary classes from the java.util package to work with lists and arrays.

2. A list of integers is created using Arrays.asList(), which serves as the source of numbers to process.

3. The list is converted into a stream using the stream() method. Streams in Java 8 provide a high-level abstraction for processing sequences of elements and support a wide range of operations, including filtering, sorting, and mapping.

4. The filter operation is used to select even numbers from the stream. It takes a lambda expression n -> n % 2 == 0 as a predicate, which returns true for even numbers.

5. The forEach terminal operation is then used to iterate over each element in the filtered stream, printing out the even numbers using System.out::println, which is a method reference to the println method of the System.out object.

6. This approach showcases the declarative programming style introduced in Java 8, allowing for concise and readable code for common tasks such as filtering a collection based on a condition and performing an action on each element of the filtered collection.

Comments