Java 8 program that filters even numbers, squares each element, and then filters out numbers greater than 50
Question:
Java 8 program that filters even numbers, squares each element, and then filters out numbers greater than 50?
Answer :
Step 1: Create a List of Numbers
- Begin by creating a list of integers. In this example, we have a list of numbers from 10 to 80.
Step 2: Use Java 8 Streams
- Utilize Java 8 streams to process the list efficiently.
Step 3: Filter Even Numbers
- Apply the
filter
operation to the stream to retain only even numbers. Even numbers are those that are divisible by 2 without a remainder.
Step 4: Square Each Element
- Use the
map
operation to square each element in the filtered list. For each even number, calculate the square (multiply by itself).
Step 5: Filter Numbers Greater Than 50
- Apply another
filter
operation to the streamed elements. In this step, we filter out numbers greater than 50.
Step 6: Collect the Result
- Utilize the
collect
operation to gather the filtered and squared numbers into a new list.
Step 7: Display the Results
- Finally, print both the original list, the filtered even numbers squared, and the filtered list with numbers greater than 50.
Here's the example code implementing these steps:
javaimport java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FilterEvenSquareAndFilter {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 15, 20, 25, 30, 35, 40);
List<Integer> evenSquaresGreaterThan50 = numbers.stream()
.filter(n -> n % 2 == 0) // Filter even numbers
.map(n -> n * n) // Square each element
.filter(n -> n > 50) // Filter numbers greater than 50
.collect(Collectors.toList());
System.out.println("Original List: " + numbers);
System.out.println("Filtered Even, Squared, and Greater Than 50: " + evenSquaresGreaterThan50);
}
}
With this code, the list numbers
includes both even and odd values. The program filters only the even numbers, squares them, and then filters the squared values that are greater than 50.
Output:
Original List: [10, 15, 20, 25, 30, 35, 40]
Filtered Even, Squared, and Greater Than 50: [100, 400, 900, 1600]
Comments
Post a Comment