Java 8提供了Stream API,可以方便地对集合进行操作和处理。要获取所有地址以P开头的员工,可以按照以下步骤进行:
public class Employee {
private String name;
private String address;
public Employee(String name, String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
}
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("John", "Palo Alto"));
employees.add(new Employee("Alice", "Paris"));
employees.add(new Employee("Peter", "Pittsburgh"));
employees.add(new Employee("Paul", "Pune"));
List<Employee> filteredEmployees = employees.stream()
.filter(employee -> employee.getAddress().startsWith("P"))
.collect(Collectors.toList());
在上述代码中,使用stream()
方法将集合转换为流,然后使用filter()
方法过滤出地址以P开头的员工,最后使用collect()
方法将结果收集到一个新的集合中。
for (Employee employee : filteredEmployees) {
System.out.println("Name: " + employee.getName() + ", Address: " + employee.getAddress());
}
这样就可以获取所有地址以P开头的员工,并打印出他们的姓名和地址。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云