1. Introduction
Filtering a list is a common operation in Java programming, where you need to extract elements that meet specific criteria from a list. Java provides multiple ways to perform filtering, especially with the advent of the Stream API in Java 8, which introduced a more functional approach. This blog post will explore different methods to filter a Java list, including loops and the Stream API.
2. Program Steps
1. Create a list of integers.
2. Filter the list to include only even numbers using a for-loop.
3. Filter the list to include only even numbers using the Stream API.
3. Code Program
import java.util.*;
import java.util.stream.Collectors;
public class FilterList {
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);
// Method 1: Filtering using a for-loop
List<Integer> evenNumbersUsingLoop = new ArrayList<>();
for (Integer number : numbers) {
if (number % 2 == 0) {
evenNumbersUsingLoop.add(number);
}
}
// Method 2: Filtering using the Stream API
List<Integer> evenNumbersUsingStream = numbers.stream()
.filter(number -> number % 2 == 0)
.collect(Collectors.toList());
// Displaying the original list
System.out.println("Original list: " + numbers);
// Displaying the filtered lists
System.out.println("Even numbers using loop: " + evenNumbersUsingLoop);
System.out.println("Even numbers using Stream API: " + evenNumbersUsingStream);
}
}
Output:
Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Even numbers using loop: [2, 4, 6, 8, 10] Even numbers using Stream API: [2, 4, 6, 8, 10]
Explanation:
1. The program starts by creating a list named numbers containing integers from 1 to 10.
2. To filter the list for even numbers using a loop, a new list evenNumbersUsingLoop is created. The program iterates over numbers using a for-each loop, adds only even numbers to evenNumbersUsingLoop.
3. The second method utilizes the Stream API introduced in Java 8. The filter operation is applied to stream elements to select only even numbers. The filtered stream is then collected into a new list evenNumbersUsingStream using Collectors.toList().
4. Both filtered lists, evenNumbersUsingLoop and evenNumbersUsingStream, contain the even numbers extracted from the original list, demonstrating the output of each filtering method.
5. This example illustrates two common approaches to filtering lists in Java, showing the imperative approach using loops and the declarative approach using the Stream API.
Comments
Post a Comment
Leave Comment