如果提供给您的数据文件包含雇员的名字和姓氏及其薪水,如何创建该数据的数组列表?另外,如何创建一种方法来搜索ArrayList中的雇员姓名(用户输入的LAST名称),以及另一种方法来搜索ArrayList中每周收入超过用户输入金额的所有雇员?
使用必填字段创建课程
如果您想在Java 8中使用filter()函数,也可能会进行检查,但是它将在该过程中创建一个流。 https://mkyong.com/java8/java-8-streams-filter-examples/
您使用的方法基本上取决于文件的大小。如果您要谈论文件中的许多记录,那么最好使用方法
First Last Salary
----- ---- -----
John Doe 78
Brad Snow 98
Bill Rosnow 101
我将建立某种数据结构来保存每一行数据,例如Employee类对象
public class Employee {
private String First;
private String Last;
private double salary;
// constructor, setters, getters down below
}
然后,您将读取每一行数据并将内容存储到对象中,并将其添加到ArrayList中
ArrayList<Employee> dataArray = new ArrayList<Employee>();
// pseudo code here
while(Not End of File) {
// Parse file line contents and separate into local variables
Employee dataLine = new Employee(firstNameFromFile, LastNameFromFile, salaryFromFile);
dataArray.add(dataLine);
}
这就是我将文件中的数据存储到ArrayList中的方式。现在要搜索数组,这取决于您希望算法的效率。您可以通过遍历数组列表中的每个对象来执行简单的线性搜索,即O(n)。可以通过以下for循环来做到这一点:
for(Employee employee : dataArray) {
if(employee.getLastName() == searchingName) return employee;
}
现在,可以为指定的薪水做同样的事情,但是您可以将找到的Employee对象存储到另一个ArrayList中;这样,您可以让所有薪水高于指定金额的员工:
ArrayList<Employee> employeesFound = new ArrayList<Employee>();
for(Employee employee : dataArray) { // Don't forget that dataArray holds all the Employee objects
if(employee.getSalary() > userSpecifiedSalary) employeesFound.add(employee);
}
return employeesFound;
希望这会有所帮助!