FLUENT COLLECTIONS's actual application case in the Java library
In the Java library, FLUENT Collections is a practical tool that can simplify the collection operation.It provides an elegant and smooth way to handle the collection elements in order to perform common collection operations more efficiently.
A practical application case of FLUENT Collection is to improve the readability and writing efficiency of code when processing large -scale data sets.Below is an example of using FLUENT Collections:
Suppose we have a data set containing employee information, we want to screen out all employees who salary within a certain range.The traditional approach may be to use For cycling to traverse the set element, and then determine whether the salary of each element meets the conditions.But using Fluent Collections, we can achieve it in a simpler and more readable way.
First, let's create an Employee class to represent employee information:
public class Employee {
private String name;
private double salary;
public Employee(String name, double salary){
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
Then, we create a collection of employee information and use the Fluent Collections to screen the employees of the salary within the specified range:
import java.util.List;
import static com.google.common.collect.FluentIterable.from;
public class Example {
public static void main(String[] args) {
// Create an employee collection
List<Employee> employees = List.of(
New Employee ("Zhang San", 5000),
New Employee ("Li Si", 7000),
New Employee ("Wang Wu", 9000),
New Employee ("Zhao Liu", 6000),
New Employee ("Liu Qi", 8000)
);
// Use FLUENT Collections Employees with a salary between 4000 and 8000
List<Employee> filteredEmployees = from(employees)
.filter(e -> e.getSalary() >= 4000 && e.getSalary() <= 8000)
.toList();
// Print screening results
System.out.println ("Employees between 4000 and 8000:");
for(Employee emp : filteredEmployees) {
System.out.println (Emp.getName () + ", salary:" + Emp.getsalary ());
}
}
}
Run the above code, the output will be the following results:
Employees with salary between 4000 and 8000:
Zhang San, salary: 5000.0
Li Si, salary: 7000.0
Zhao Liu, salary: 6000.0
Liu Qi, salary: 8000.0
By using Fluent Collections, we can use chain calls to screen for qualified employees, and the code is more concise and easy to read.
All in all, the practical cases of Fluent Collections in the Java class library are to perform efficient operations of the collection.By using Fluent Collections, we can process the collection elements in a more concise and more readable way to improve the readability and writing efficiency of the code.