Find Squares of First Three Even Numbers in Java 8

Learn how to find squares of first three even numbers in Java 8 using Stream API,In this example, we will find the first three even numbers from a list, square them using the map() method, and collect the results into a new list.

Code Explanation (Step-by-Step)

  • Arrays.asList() creates a list of integer values.
  • number.stream() converts the list into a Stream for processing.
  • filter(a -> a % 2 == 0) selects only even numbers from the list.
  • map(b -> b * b) converts each even number into its square.
  • limit(3) keeps only the first three squared even numbers.
  • collect(Collectors.toList()) collects the processed elements into a new list.
  • Print the squares of first three even numbers.
				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SquareTest {

    public static void main(String[] args) {

        List<Integer> number = Arrays.asList(4, 23, 20, 45, 30, 123, 100);

        List<Integer> listNumber = number.stream()
                .filter(a -> a % 2 == 0)
                .map(b -> b * b)
                .limit(3)
                .collect(Collectors.toList());

        System.out.println("Squares of the first three even numbers are: " + listNumber);
    }
}
				
			

Output :
Squares of the first three even numbers are: [16, 400, 900]

Java 8 Program to Square Numbers Using map()

				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SquareNumbersExample {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(2, 3, 4, 5, 6);

        List<Integer> squaredNumbers = numbers.stream()
                .map(n -> n * n)
                .collect(Collectors.toList());

        System.out.println("Squared Numbers: " + squaredNumbers);
    }
}
				
			

Output :
Squared Numbers: [4, 9, 16, 25, 36]

FAQ
How do you find even numbers using Java 8 Stream API?
Use the filter() method with the condition n -> n % 2 == 0 to select even numbers from a stream.
What is the purpose of the map() method in Java 8?
The map() method transforms each element in a stream. In this example, it converts each even number into its square.
Why is limit(3) used in the program?
The limit(3) method restricts the stream to the first three processed elements.
What does collect(Collectors.toList()) do?
It gathers all processed stream elements into a new List.
Can I square odd numbers using the same approach?
Yes, replace the filter condition with n -> n % 2 != 0 to process odd numbers instead.