How to filter a collection using Java streams?
In Java, you can use Stream to filter collections. The filter() method provided by Stream allows you to filter elements in a collection based on specified conditions. Here is an example code:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 过滤出偶数
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // 输出 [2, 4, 6, 8, 10]
}
}
In the example above, we first create a list containing integers. Then, we convert the list into a stream using the stream() method. Next, we use the filter() method with a Lambda expression as a parameter to filter out even numbers. Finally, we use the collect() method to gather the filtered elements into a new list.
With the filter() method, you can filter out elements that meet custom conditions.