如何在ArrayList中搜索员工姓名(仅搜索姓氏)

问题描述 投票:-1回答:2

如果提供给您的数据文件包含雇员的名字和姓氏及其薪水,如何创建该数据的数组列表?另外,如何创建一种方法来搜索ArrayList中的雇员姓名(用户输入的LAST名称),以及另一种方法来搜索ArrayList中每周收入超过用户输入金额的所有雇员?

java inheritance arraylist
2个回答
0
投票
我将创建一个包含名字,姓氏和薪水的类。如果名字对您根本没有关系,您也可以将其存储在HashMap中,这将使搜索变得容易,但是如果其中有两次姓氏被覆盖,则会出现问题。

使用必填字段创建课程

    创建一个ArrayList
  1. 读取文件,为文件中的每个条目创建一个对象,然后将该对象添加到数组中
  • 搜索姓氏:通过foreach循环遍历列表,并将姓氏与搜索字符串进行比较。如果匹配->做您需要的任何事情,例如System.out.printLine。
  • 搜索薪水:通过foreach循环遍历列表,并检查当前对象的薪水是否> =您的参考薪水。然后将其打印或根据需要将其添加到另一个数组中

    如果您想在Java 8中使用filter()函数,也可能会进行检查,但是它将在该过程中创建一个流。 https://mkyong.com/java8/java-8-streams-filter-examples/

    您使用的方法基本上取决于文件的大小。如果您要谈论文件中的许多记录,那么最好使用方法


  • 0
    投票
    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;
    

    希望这会有所帮助!

    © www.soinside.com 2019 - 2024. All rights reserved.