How to find one element of the object in arraylist of objects?

tadziuuuuu :

I have an arraylist of Employee class objects. Every employee has id, fname, lname etc. I need to get index of element where employee ID's is for example 1234521953. How to find out the index in which the employee is located? Every ID is unique that's why I am truing to find him by ID.

public class Employee extends Person {
    private String employerName;
    private LocalDate employmentDate;
    private LocalDate releaseDate;
    private BigDecimal salary;
    private String jobtitle;    
}

There is my class Person:

public class Person {
    public long getId() {
        return id;
    }

    private long id;
    private String fname;
    private String lname;
    private String addressLine;
    private LocalDate birthDate;
}

I am adding them in for to:

List<Employee> employeesAL = new ArrayList<>();
azro :

If you have implemented the .equals method in Employee class you may just pass it to .indexOf()

List<Employee> l = new ArrayList<>();
Employee e = new Employee("ID123");
int idx = l.indexOf(e);

As the ID is unique, you don't need to check all the fields in the .equals() method, just check the ID :

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Employee employee = (Employee) o;
    return id == employee.id;
}

Or implement it yourself, using the same logic of indexOf

int idx = -1;
for (int i = 0; i < l.size(); i++) {
    if (e.getId() == l.get(i).getId()) {
        idx = i;
        break;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=355732&siteId=1