How to filter data in Java Stream?
In Java, you can use Streams to filter data. Streams offer a filter() method that allows you to specify filter conditions using Lambda expressions.
Here is an example demonstrating how to use a Stream to filter a list of integers, keeping only elements greater than 10:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(10);
numbers.add(15);
numbers.add(20);
List<Integer> filteredNumbers = numbers.stream()
.filter(n -> n > 10)
.collect(Collectors.toList());
System.out.println(filteredNumbers); // 输出 [15, 20]
}
}
In the above example, an integer list called numbers is first created, and then converted into a Stream using the stream() method. Next, a Lambda expression is passed into the filter() method to filter out elements greater than 10. Finally, the collect() method is used to gather the filtered elements into a new list.
By running the above code, it will output the filtered list [15, 20].