In Java programming, we often need to filter the sets to filter out elements that meet specific conditions. The Stream API introduced by Java 8 provides us with an elegant way to process collection data. In this article, we will explain how to use Java StreamfilterMethod to filter elements in List collection.
1. Create a sample List
First, let's create a List collection containing some sample data. Suppose we have a List containing integers as follows:
List<Integer> numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
2. Use Stream's filter method to filter
Next, we will use Stream'sfilterMethod to filter out even numbers in List. The sample code is as follows:
List<Integer> evenNumbers = () .filter(num -> num % 2 == 0) .collect(()); ("Even list:" + evenNumbers);
In the above code, we first convert List to Stream and then callfilterThe method passes in a Lambda expression that defines the filtering condition: only elements that can be divisible by 2 (i.e. even numbers). Finally, we usecollect(())Method collects the filtered results into a new List.
3. Custom filtering conditions
In addition to filtering even numbers, we can also filter elements in List according to custom conditions. For example, we can filter out numbers greater than 5. The sample code is as follows:
List<Integer> numbersGreaterThan5 = () .filter(num -> num > 5) .collect(()); ("List of numbers greater than 5:" + numbersGreaterThan5);
Filter out elements that meet specific criteria from a List containing objects. For example, suppose we have a List containing employee information and we want to screen employees over 30 based on the employee's age. Here is a sample code for a practical application scenario:
1. Define Employee class
First, we define an Employee class to represent employee information, including two attributes:
public class Employee { private String name; private int age; public Employee(String name, int age) { = name; = age; } public String getName() { return name; } public int getAge() { return age; } }
2. Create a List containing Employee object
Next, we create a List containing the Employee object:
List<Employee> employees = new ArrayList<>(); (new Employee("Alice", 28)); (new Employee("Bob", 35)); (new Employee("Carol", 30)); (new Employee("David", 40));
3. Use Stream's filter method for age filter
Then we use Java StreamfilterMethods: Employees over 30 years old are selected according to their age:
List<Employee> employeesAbove30 = () .filter(emp -> () > 30) .collect(());
4. Output filter results
Finally, we output the filtered information of employees over 30 years old:
("Information of employees over 30:"); for(Employee emp : employeesAbove30) { ("Name:" + () + ",age:" + ()); }
Through the above code example, we have implemented the function of filtering employee information based on age. This Java Stream-based data filtering method can help us quickly and concisely process collection data, improving the readability and maintainability of our code. Hope this example helps you!
The Stream API introduced in Java 8 provides a completely new way to process collection data. Java Stream allows us to process collections in a declarative manner, making the code more concise, easy to read and efficient.
Main features:
- Pipeline operation:Stream allows us to convert a collection into a pipeline through a series of intermediate operations (e.g.filter、map、distinctetc.) and terminal operations (e.g.collect、forEach、reduceetc.) to process the data.
- Lazy evaluation: Stream operations are usually performed lazy and will trigger actual calculations only when terminal operations are encountered, which helps improve performance.
- Parallel processing: Stream provides the ability to process collection data in parallel, throughparallel()Methods can convert streams into parallel streams, utilizing multi-core processors to accelerate computation.
Main operation method:
- Intermediate operation:
- filter(Predicate): Receive a Predicate function to filter elements.
- map(Function): Receive a Function function to perform mapping operations on each element.
- distinct(): Remove duplicate elements.
- sorted(): Sort elements.
- limit(long): Limit the number of returned elements.
- skip(long): Skip the specified number of elements.
- Terminal operation:
- forEach(Consumer): Perform an operation on each element.
- collect(Collectors): Convert streams to other collections or data structures.
- reduce(BinaryOperator): Reduce all elements to get a result.
- count(): Returns the number of elements in the stream.
- anyMatch(Predicate)、allMatch(Predicate)、noneMatch(Predicate): Elements that determine whether there are, all satisfy, and all the elements that do not meet the given conditions.
Sample code:
List<Integer> numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); int sum = () .filter(num -> num % 2 == 0) .map(num -> num * 2) .reduce(0, Integer::sum); ("The sum of even elements multiplied by 2 is:" + sum);
The above code demonstrates the use of the Stream API to filter, map and reduce even elements in a collection, and finally get the sum of even elements multiplied by 2. Through the Stream API, we can write collection processing code more elegantly and improve the readability and maintainability of the code.
4. Conclusion
By using Java StreamfilterMethod, we can easily filter elements in List collections, thus achieving flexible data filtering. This functional programming style operation makes the code more readable and concise, and improves the maintainability and scalability of the code. Hope this article helps you better understand how to use Java StreamfilterMethod filters List collection.
This is the end of this article about the implementation of java streamfilter list filtering. For more related java streamfilter list filtering content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!